Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.
 
 
 

3194 rindas
76 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.configure(arguments[0]);
  730. }
  731. configure(args) {
  732. // Make a this.config, that has stuff like showTooltip,
  733. // showLegend, which then all functions will check
  734. this.setColors();
  735. // constants
  736. this.config = {
  737. showTooltip: 1, // calculate
  738. showLegend: 1,
  739. isNavigable: 0,
  740. // animate: 1
  741. animate: 0
  742. };
  743. this.state = {
  744. colors: this.colors
  745. };
  746. }
  747. setColors() {
  748. let args = this.rawChartArgs;
  749. // Needs structure as per only labels/datasets, from config
  750. const list = args.type === 'percentage' || args.type === 'pie'
  751. ? args.data.labels
  752. : args.data.datasets;
  753. if(!args.colors || (list && args.colors.length < list.length)) {
  754. this.colors = DEFAULT_COLORS;
  755. } else {
  756. this.colors = args.colors;
  757. }
  758. this.colors = this.colors.map(color => getColor(color));
  759. }
  760. setMargins() {
  761. // TODO: think for all
  762. let height = this.argHeight;
  763. this.baseHeight = height;
  764. this.height = height - 40; // change
  765. this.translateY = 20;
  766. this.setHorizontalMargin();
  767. }
  768. setHorizontalMargin() {
  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. if(!this.parseData()) {
  778. return false;
  779. }
  780. return true;
  781. }
  782. parseData() {
  783. let data = this.rawChartArgs.data;
  784. let valid = this.checkData(data);
  785. if(!valid) return false;
  786. this.data = data;
  787. return true;
  788. }
  789. setup() {
  790. if(this.validate()) {
  791. this._setup();
  792. }
  793. }
  794. _setup() {
  795. this.bindWindowEvents();
  796. this.setupConstants();
  797. this.setMargins();
  798. this.makeContainer();
  799. this.makeTooltip(); // without binding
  800. this.calcWidth();
  801. this.makeChartArea();
  802. this.initComponents();
  803. this.setupComponents();
  804. this.draw(true);
  805. }
  806. bindWindowEvents() {
  807. window.addEventListener('resize orientationchange', () => this.draw());
  808. }
  809. setupConstants() {}
  810. setupComponents() {
  811. // Components config
  812. this.components = [];
  813. }
  814. makeContainer() {
  815. this.container = $$1.create('div', {
  816. className: 'chart-container',
  817. innerHTML: `<h6 class="title">${this.title}</h6>
  818. <h6 class="sub-title uppercase">${this.subtitle}</h6>
  819. <div class="frappe-chart graphics"></div>
  820. <div class="graph-stats-container"></div>`
  821. });
  822. // Chart needs a dedicated parent element
  823. this.parent.innerHTML = '';
  824. this.parent.appendChild(this.container);
  825. this.chartWrapper = this.container.querySelector('.frappe-chart');
  826. this.statsWrapper = this.container.querySelector('.graph-stats-container');
  827. }
  828. makeTooltip() {
  829. this.tip = new SvgTip({
  830. parent: this.chartWrapper,
  831. colors: this.colors
  832. });
  833. this.bindTooltip();
  834. }
  835. bindTooltip() {}
  836. draw(init=false) {
  837. this.components.forEach(c => c.make()); // or c.build()
  838. this.renderLegend();
  839. this.setupNavigation(init);
  840. // TODO: remove timeout and decrease post animate time in chart component
  841. setTimeout(() => {this.update();}, 1000);
  842. }
  843. calcWidth() {
  844. let outerAnnotationsWidth = 0;
  845. // let charWidth = 8;
  846. // this.specificValues.map(val => {
  847. // let strWidth = getStringWidth((val.title + ""), charWidth);
  848. // if(strWidth > outerAnnotationsWidth) {
  849. // outerAnnotationsWidth = strWidth - 40;
  850. // }
  851. // });
  852. this.baseWidth = getElementContentWidth(this.parent) - outerAnnotationsWidth;
  853. this.width = this.baseWidth - (this.translateXLeft + this.translateXRight);
  854. }
  855. update(data=this.data) {
  856. this.prepareData(data);
  857. this.calc(); // builds state
  858. this.render();
  859. }
  860. prepareData() {}
  861. renderConstants() {}
  862. calc() {} // builds state
  863. render(animate=true) {
  864. // Can decouple to this.refreshComponents() first to save animation timeout
  865. this.elementsToAnimate = [].concat.apply([],
  866. this.components.map(c => c.update(animate)));
  867. if(this.elementsToAnimate) {
  868. runSMILAnimation(this.chartWrapper, this.svg, this.elementsToAnimate);
  869. }
  870. // TODO: rebind new units
  871. // if(this.isNavigable) {
  872. // this.bind_units(units_array);
  873. // }
  874. }
  875. makeChartArea() {
  876. this.svg = makeSVGContainer(
  877. this.chartWrapper,
  878. 'chart',
  879. this.baseWidth,
  880. this.baseHeight
  881. );
  882. this.svgDefs = makeSVGDefs(this.svg);
  883. // I WISH !!!
  884. // this.svg = makeSVGGroup(
  885. // svgContainer,
  886. // 'flipped-coord-system',
  887. // `translate(0, ${this.baseHeight}) scale(1, -1)`
  888. // );
  889. this.drawArea = makeSVGGroup(
  890. this.svg,
  891. this.type + '-chart',
  892. `translate(${this.translateXLeft}, ${this.translateY})`
  893. );
  894. }
  895. renderLegend() {}
  896. setupNavigation(init=false) {
  897. if(this.isNavigable) return;
  898. this.makeOverlay();
  899. if(init) {
  900. this.bindOverlay();
  901. document.addEventListener('keydown', (e) => {
  902. if(isElementInViewport(this.chartWrapper)) {
  903. e = e || window.event;
  904. if (e.keyCode == '37') {
  905. this.onLeftArrow();
  906. } else if (e.keyCode == '39') {
  907. this.onRightArrow();
  908. } else if (e.keyCode == '38') {
  909. this.onUpArrow();
  910. } else if (e.keyCode == '40') {
  911. this.onDownArrow();
  912. } else if (e.keyCode == '13') {
  913. this.onEnterKey();
  914. }
  915. }
  916. });
  917. }
  918. }
  919. makeOverlay() {}
  920. bindOverlay() {}
  921. bind_units() {}
  922. onLeftArrow() {}
  923. onRightArrow() {}
  924. onUpArrow() {}
  925. onDownArrow() {}
  926. onEnterKey() {}
  927. // updateData() {
  928. // update();
  929. // }
  930. getDataPoint() {}
  931. setCurrentDataPoint() {}
  932. // Update the data here, then do relevant updates
  933. // and drawing in child classes by overriding
  934. // The Child chart will only know what a particular update means
  935. // and what components are affected,
  936. // BaseChart shouldn't be doing the animating
  937. updateDataset(dataset, index) {}
  938. updateDatasets(datasets) {
  939. //
  940. }
  941. addDataset(dataset, index) {}
  942. removeDataset(index = 0) {}
  943. addDataPoint(dataPoint, index = 0) {}
  944. removeDataPoint(index = 0) {}
  945. updateDataPoint(dataPoint, index = 0) {}
  946. getDifferentChart(type) {
  947. return getDifferentChart(type, this.type, this.rawChartArgs);
  948. }
  949. }
  950. const Y_AXIS_MARGIN = 60;
  951. class ChartComponent$1 {
  952. constructor({
  953. layerClass = '',
  954. layerTransform = '',
  955. parent,
  956. constants,
  957. data,
  958. // called on update
  959. makeElements,
  960. postMake,
  961. getData,
  962. animateElements
  963. }) {
  964. this.parent = parent;
  965. this.layerTransform = layerTransform;
  966. this.constants = constants;
  967. this.makeElements = makeElements;
  968. this.postMake = postMake;
  969. this.getData = getData;
  970. this.animateElements = animateElements;
  971. this.store = [];
  972. layerClass = typeof(layerClass) === 'function'
  973. ? layerClass() : layerClass;
  974. this.layer = makeSVGGroup(this.parent, layerClass, this.layerTransform);
  975. this.data = data;
  976. this.make();
  977. }
  978. refresh(data) {
  979. this.data = data || this.getData();
  980. }
  981. make() {
  982. this.preMake && this.preMake();
  983. this.render(this.data);
  984. this.postMake && this.postMake();
  985. this.oldData = this.data;
  986. }
  987. render(data) {
  988. this.store = this.makeElements(data);
  989. this.layer.textContent = '';
  990. this.store.forEach(element => {
  991. this.layer.appendChild(element);
  992. });
  993. }
  994. update(animate = true) {
  995. this.refresh();
  996. let animateElements = [];
  997. if(animate) {
  998. animateElements = this.animateElements(this.data);
  999. }
  1000. // TODO: Can we remove this?
  1001. setTimeout(() => {
  1002. this.make();
  1003. }, 1400);
  1004. return animateElements;
  1005. }
  1006. }
  1007. let componentConfigs = {
  1008. yAxis: {
  1009. layerClass: 'y axis',
  1010. makeElements(data) {
  1011. return data.positions.map((position, i) =>
  1012. yLine(position, data.labels[i], this.constants.width,
  1013. {mode: this.constants.mode, pos: this.constants.pos})
  1014. );
  1015. },
  1016. animateElements(newData) {
  1017. let newPos = newData.positions;
  1018. let newLabels = newData.labels;
  1019. let oldPos = this.oldData.positions;
  1020. let oldLabels = this.oldData.labels;
  1021. [oldPos, newPos] = equilizeNoOfElements(oldPos, newPos);
  1022. [oldLabels, newLabels] = equilizeNoOfElements(oldLabels, newLabels);
  1023. this.render({
  1024. positions: oldPos,
  1025. labels: newLabels
  1026. });
  1027. return this.store.map((line, i) => {
  1028. return translateHoriLine(
  1029. line, newPos[i], oldPos[i]
  1030. );
  1031. });
  1032. }
  1033. },
  1034. xAxis: {
  1035. layerClass: 'x axis',
  1036. makeElements(data) {
  1037. return data.positions.map((position, i) =>
  1038. xLine(position, data.labels[i], this.constants.height,
  1039. {mode: this.constants.mode, pos: this.constants.pos})
  1040. );
  1041. },
  1042. animateElements(newData) {
  1043. let newPos = newData.positions;
  1044. let newLabels = newData.labels;
  1045. let oldPos = this.oldData.positions;
  1046. let oldLabels = this.oldData.labels;
  1047. [oldPos, newPos] = equilizeNoOfElements(oldPos, newPos);
  1048. [oldLabels, newLabels] = equilizeNoOfElements(oldLabels, newLabels);
  1049. this.render({
  1050. positions: oldPos,
  1051. labels: newLabels
  1052. });
  1053. return this.store.map((line, i) => {
  1054. return translateVertLine(
  1055. line, newPos[i], oldPos[i]
  1056. );
  1057. });
  1058. }
  1059. },
  1060. yMarkers: {
  1061. layerClass: 'y-markers',
  1062. makeElements(data) {
  1063. return data.map(marker =>
  1064. yMarker(marker.position, marker.label, this.constants.width,
  1065. {pos:'right', mode: 'span', lineType: 'dashed'})
  1066. );
  1067. },
  1068. animateElements(newData) {
  1069. [this.oldData, newData] = equilizeNoOfElements(this.oldData, newData);
  1070. let newPos = newData.map(d => d.position);
  1071. let newLabels = newData.map(d => d.label);
  1072. let oldPos = this.oldData.map(d => d.position);
  1073. let oldLabels = this.oldData.map(d => d.label);
  1074. this.render(oldPos.map((pos, i) => {
  1075. return {
  1076. position: oldPos[i],
  1077. label: newLabels[i]
  1078. }
  1079. }));
  1080. return this.store.map((line, i) => {
  1081. return translateHoriLine(
  1082. line, newPos[i], oldPos[i]
  1083. );
  1084. });
  1085. }
  1086. },
  1087. yRegions: {
  1088. layerClass: 'y-regions',
  1089. makeElements(data) {
  1090. return data.map(region =>
  1091. yRegion(region.start, region.end, this.constants.width,
  1092. region.label)
  1093. );
  1094. },
  1095. animateElements(newData) {
  1096. [this.oldData, newData] = equilizeNoOfElements(this.oldData, newData);
  1097. let newPos = newData.map(d => d.end);
  1098. let newLabels = newData.map(d => d.label);
  1099. let newStarts = newData.map(d => d.start);
  1100. let oldPos = this.oldData.map(d => d.end);
  1101. let oldLabels = this.oldData.map(d => d.label);
  1102. let oldStarts = this.oldData.map(d => d.start);
  1103. this.render(oldPos.map((pos, i) => {
  1104. return {
  1105. start: oldStarts[i],
  1106. end: oldPos[i],
  1107. label: newLabels[i]
  1108. }
  1109. }));
  1110. let animateElements = [];
  1111. this.store.map((rectGroup, i) => {
  1112. animateElements = animateElements.concat(animateRegion(
  1113. rectGroup, newStarts[i], newPos[i], oldPos[i]
  1114. ));
  1115. });
  1116. return animateElements;
  1117. }
  1118. },
  1119. barGraph: {
  1120. // opt:[
  1121. // 'barGraph',
  1122. // this.drawArea,
  1123. // {
  1124. // controller: barController,
  1125. // index: index,
  1126. // color: this.colors[index],
  1127. // valuesOverPoints: this.valuesOverPoints,
  1128. // stacked: this.barOptions && this.barOptions.stacked,
  1129. // spaceRatio: 0.5,
  1130. // minHeight: this.height * MIN_BAR_PERCENT_HEIGHT
  1131. // },
  1132. // {
  1133. // barsWidth: this.state.unitWidth * (1 - spaceRatio),
  1134. // barWidth: barsWidth/(stacked ? 1 : this.state.noOfDatasets),
  1135. // },
  1136. // function() {
  1137. // let s = this.state;
  1138. // return {
  1139. // barsWidth: this.state.unitWidth * (1 - spaceRatio),
  1140. // barWidth: barsWidth/(stacked ? 1 : this.state.noOfDatasets),
  1141. // positions: s.xAxisPositions,
  1142. // labels: s.xAxisLabels,
  1143. // }
  1144. // }.bind(this)
  1145. // ],
  1146. layerClass() { return 'y-regions' + this.constants.index; },
  1147. makeElements(data) {
  1148. let c = this.constants;
  1149. return data.yPositions.map((y, j) =>
  1150. barController.draw(
  1151. data.xPositions[j],
  1152. y,
  1153. color,
  1154. (c.valuesOverPoints ? (c.stacked ? data.cumulativeYs[j] : data.values[j]) : ''),
  1155. j,
  1156. y - (data.cumulativePositions ? data.cumulativePositions[j] : y)
  1157. )
  1158. );
  1159. },
  1160. postMake() {
  1161. if((!this.constants.stacked)) {
  1162. this.layer.setAttribute('transform',
  1163. `translate(${unitRenderer.consts.width * index}, 0)`);
  1164. }
  1165. },
  1166. animateElements(newData) {
  1167. [this.oldData, newData] = equilizeNoOfElements(this.oldData, newData);
  1168. let newPos = newData.map(d => d.end);
  1169. let newLabels = newData.map(d => d.label);
  1170. let newStarts = newData.map(d => d.start);
  1171. let oldPos = this.oldData.map(d => d.end);
  1172. let oldLabels = this.oldData.map(d => d.label);
  1173. let oldStarts = this.oldData.map(d => d.start);
  1174. this.render(oldPos.map((pos, i) => {
  1175. return {
  1176. start: oldStarts[i],
  1177. end: oldPos[i],
  1178. label: newLabels[i]
  1179. }
  1180. }));
  1181. let animateElements = [];
  1182. this.store.map((rectGroup, i) => {
  1183. animateElements = animateElements.concat(animateRegion(
  1184. rectGroup, newStarts[i], newPos[i], oldPos[i]
  1185. ));
  1186. });
  1187. return animateElements;
  1188. }
  1189. },
  1190. lineGraph: {
  1191. }
  1192. };
  1193. function getComponent(name, parent, constants, initData, getData) {
  1194. let config = componentConfigs[name];
  1195. Object.assign(config, {
  1196. parent: parent,
  1197. constants: constants,
  1198. data: initData,
  1199. getData: getData
  1200. });
  1201. return new ChartComponent$1(config);
  1202. }
  1203. function getPaths(yList, xList, color, heatline=false, regionFill=false) {
  1204. let pointsList = yList.map((y, i) => (xList[i] + ',' + y));
  1205. let pointsStr = pointsList.join("L");
  1206. let path = makePath("M"+pointsStr, 'line-graph-path', color);
  1207. // HeatLine
  1208. if(heatline) {
  1209. let gradient_id = makeGradient(this.svgDefs, color);
  1210. path.style.stroke = `url(#${gradient_id})`;
  1211. }
  1212. let components = [path];
  1213. // Region
  1214. if(regionFill) {
  1215. let gradient_id_region = makeGradient(this.svgDefs, color, true);
  1216. let zeroLine = this.state.yAxis.zeroLine;
  1217. // TODO: use zeroLine OR minimum
  1218. let pathStr = "M" + `0,${zeroLine}L` + pointsStr + `L${this.width},${zeroLine}`;
  1219. components.push(makePath(pathStr, `region-fill`, 'none', `url(#${gradient_id_region})`));
  1220. }
  1221. return components;
  1222. }
  1223. // class BarChart extends AxisChart {
  1224. // constructor(args) {
  1225. // super(args);
  1226. // this.type = 'bar';
  1227. // this.setup();
  1228. // }
  1229. // configure(args) {
  1230. // super.configure(args);
  1231. // this.config.xAxisMode = args.xAxisMode || 'tick';
  1232. // this.config.yAxisMode = args.yAxisMode || 'span';
  1233. // }
  1234. // // =================================
  1235. // makeOverlay() {
  1236. // // Just make one out of the first element
  1237. // let index = this.xAxisLabels.length - 1;
  1238. // let unit = this.y[0].svg_units[index];
  1239. // this.setCurrentDataPoint(index);
  1240. // if(this.overlay) {
  1241. // this.overlay.parentNode.removeChild(this.overlay);
  1242. // }
  1243. // this.overlay = unit.cloneNode();
  1244. // this.overlay.style.fill = '#000000';
  1245. // this.overlay.style.opacity = '0.4';
  1246. // this.drawArea.appendChild(this.overlay);
  1247. // }
  1248. // bindOverlay() {
  1249. // // on event, update overlay
  1250. // this.parent.addEventListener('data-select', (e) => {
  1251. // this.update_overlay(e.svg_unit);
  1252. // });
  1253. // }
  1254. // bind_units(units_array) {
  1255. // units_array.map(unit => {
  1256. // unit.addEventListener('click', () => {
  1257. // let index = unit.getAttribute('data-point-index');
  1258. // this.setCurrentDataPoint(index);
  1259. // });
  1260. // });
  1261. // }
  1262. // update_overlay(unit) {
  1263. // let attributes = [];
  1264. // Object.keys(unit.attributes).map(index => {
  1265. // attributes.push(unit.attributes[index]);
  1266. // });
  1267. // attributes.filter(attr => attr.specified).map(attr => {
  1268. // this.overlay.setAttribute(attr.name, attr.nodeValue);
  1269. // });
  1270. // this.overlay.style.fill = '#000000';
  1271. // this.overlay.style.opacity = '0.4';
  1272. // }
  1273. // onLeftArrow() {
  1274. // this.setCurrentDataPoint(this.currentIndex - 1);
  1275. // }
  1276. // onRightArrow() {
  1277. // this.setCurrentDataPoint(this.currentIndex + 1);
  1278. // }
  1279. // }
  1280. function normalize(x) {
  1281. // Calculates mantissa and exponent of a number
  1282. // Returns normalized number and exponent
  1283. // https://stackoverflow.com/q/9383593/6495043
  1284. if(x===0) {
  1285. return [0, 0];
  1286. }
  1287. if(isNaN(x)) {
  1288. return {mantissa: -6755399441055744, exponent: 972};
  1289. }
  1290. var sig = x > 0 ? 1 : -1;
  1291. if(!isFinite(x)) {
  1292. return {mantissa: sig * 4503599627370496, exponent: 972};
  1293. }
  1294. x = Math.abs(x);
  1295. var exp = Math.floor(Math.log10(x));
  1296. var man = x/Math.pow(10, exp);
  1297. return [sig * man, exp];
  1298. }
  1299. function getChartRangeIntervals(max, min=0) {
  1300. let upperBound = Math.ceil(max);
  1301. let lowerBound = Math.floor(min);
  1302. let range = upperBound - lowerBound;
  1303. let noOfParts = range;
  1304. let partSize = 1;
  1305. // To avoid too many partitions
  1306. if(range > 5) {
  1307. if(range % 2 !== 0) {
  1308. upperBound++;
  1309. // Recalc range
  1310. range = upperBound - lowerBound;
  1311. }
  1312. noOfParts = range/2;
  1313. partSize = 2;
  1314. }
  1315. // Special case: 1 and 2
  1316. if(range <= 2) {
  1317. noOfParts = 4;
  1318. partSize = range/noOfParts;
  1319. }
  1320. // Special case: 0
  1321. if(range === 0) {
  1322. noOfParts = 5;
  1323. partSize = 1;
  1324. }
  1325. let intervals = [];
  1326. for(var i = 0; i <= noOfParts; i++){
  1327. intervals.push(lowerBound + partSize * i);
  1328. }
  1329. return intervals;
  1330. }
  1331. function getChartIntervals(maxValue, minValue=0) {
  1332. let [normalMaxValue, exponent] = normalize(maxValue);
  1333. let normalMinValue = minValue ? minValue/Math.pow(10, exponent): 0;
  1334. // Allow only 7 significant digits
  1335. normalMaxValue = normalMaxValue.toFixed(6);
  1336. let intervals = getChartRangeIntervals(normalMaxValue, normalMinValue);
  1337. intervals = intervals.map(value => value * Math.pow(10, exponent));
  1338. return intervals;
  1339. }
  1340. function calcChartIntervals(values, withMinimum=false) {
  1341. //*** Where the magic happens ***
  1342. // Calculates best-fit y intervals from given values
  1343. // and returns the interval array
  1344. let maxValue = Math.max(...values);
  1345. let minValue = Math.min(...values);
  1346. // Exponent to be used for pretty print
  1347. let exponent = 0, intervals = []; // eslint-disable-line no-unused-vars
  1348. function getPositiveFirstIntervals(maxValue, absMinValue) {
  1349. let intervals = getChartIntervals(maxValue);
  1350. let intervalSize = intervals[1] - intervals[0];
  1351. // Then unshift the negative values
  1352. let value = 0;
  1353. for(var i = 1; value < absMinValue; i++) {
  1354. value += intervalSize;
  1355. intervals.unshift((-1) * value);
  1356. }
  1357. return intervals;
  1358. }
  1359. // CASE I: Both non-negative
  1360. if(maxValue >= 0 && minValue >= 0) {
  1361. exponent = normalize(maxValue)[1];
  1362. if(!withMinimum) {
  1363. intervals = getChartIntervals(maxValue);
  1364. } else {
  1365. intervals = getChartIntervals(maxValue, minValue);
  1366. }
  1367. }
  1368. // CASE II: Only minValue negative
  1369. else if(maxValue > 0 && minValue < 0) {
  1370. // `withMinimum` irrelevant in this case,
  1371. // We'll be handling both sides of zero separately
  1372. // (both starting from zero)
  1373. // Because ceil() and floor() behave differently
  1374. // in those two regions
  1375. let absMinValue = Math.abs(minValue);
  1376. if(maxValue >= absMinValue) {
  1377. exponent = normalize(maxValue)[1];
  1378. intervals = getPositiveFirstIntervals(maxValue, absMinValue);
  1379. } else {
  1380. // Mirror: maxValue => absMinValue, then change sign
  1381. exponent = normalize(absMinValue)[1];
  1382. let posIntervals = getPositiveFirstIntervals(absMinValue, maxValue);
  1383. intervals = posIntervals.map(d => d * (-1));
  1384. }
  1385. }
  1386. // CASE III: Both non-positive
  1387. else if(maxValue <= 0 && minValue <= 0) {
  1388. // Mirrored Case I:
  1389. // Work with positives, then reverse the sign and array
  1390. let pseudoMaxValue = Math.abs(minValue);
  1391. let pseudoMinValue = Math.abs(maxValue);
  1392. exponent = normalize(pseudoMaxValue)[1];
  1393. if(!withMinimum) {
  1394. intervals = getChartIntervals(pseudoMaxValue);
  1395. } else {
  1396. intervals = getChartIntervals(pseudoMaxValue, pseudoMinValue);
  1397. }
  1398. intervals = intervals.reverse().map(d => d * (-1));
  1399. }
  1400. return intervals;
  1401. }
  1402. function getZeroIndex(yPts) {
  1403. let zeroIndex;
  1404. let interval = getIntervalSize(yPts);
  1405. if(yPts.indexOf(0) >= 0) {
  1406. // the range has a given zero
  1407. // zero-line on the chart
  1408. zeroIndex = yPts.indexOf(0);
  1409. } else if(yPts[0] > 0) {
  1410. // Minimum value is positive
  1411. // zero-line is off the chart: below
  1412. let min = yPts[0];
  1413. zeroIndex = (-1) * min / interval;
  1414. } else {
  1415. // Maximum value is negative
  1416. // zero-line is off the chart: above
  1417. let max = yPts[yPts.length - 1];
  1418. zeroIndex = (-1) * max / interval + (yPts.length - 1);
  1419. }
  1420. return zeroIndex;
  1421. }
  1422. function getRealIntervals(max, noOfIntervals, min = 0, asc = 1) {
  1423. let range = max - min;
  1424. let part = range * 1.0 / noOfIntervals;
  1425. let intervals = [];
  1426. for(var i = 0; i <= noOfIntervals; i++) {
  1427. intervals.push(min + part * i);
  1428. }
  1429. return asc ? intervals : intervals.reverse();
  1430. }
  1431. function getIntervalSize(orderedArray) {
  1432. return orderedArray[1] - orderedArray[0];
  1433. }
  1434. function getValueRange(orderedArray) {
  1435. return orderedArray[orderedArray.length-1] - orderedArray[0];
  1436. }
  1437. function calcDistribution(values, distributionSize) {
  1438. // Assume non-negative values,
  1439. // implying distribution minimum at zero
  1440. let dataMaxValue = Math.max(...values);
  1441. let distributionStep = 1 / (distributionSize - 1);
  1442. let distribution = [];
  1443. for(var i = 0; i < distributionSize; i++) {
  1444. let checkpoint = dataMaxValue * (distributionStep * i);
  1445. distribution.push(checkpoint);
  1446. }
  1447. return distribution;
  1448. }
  1449. function getMaxCheckpoint(value, distribution) {
  1450. return distribution.filter(d => d < value).length;
  1451. }
  1452. class AxisChart extends BaseChart {
  1453. constructor(args) {
  1454. super(args);
  1455. this.isSeries = args.isSeries;
  1456. this.valuesOverPoints = args.valuesOverPoints;
  1457. this.formatTooltipY = args.formatTooltipY;
  1458. this.formatTooltipX = args.formatTooltipX;
  1459. this.barOptions = args.barOptions;
  1460. this.lineOptions = args.lineOptions;
  1461. this.type = args.type || 'line';
  1462. this.xAxisMode = args.xAxisMode || 'span';
  1463. this.yAxisMode = args.yAxisMode || 'span';
  1464. this.zeroLine = this.height;
  1465. this.setPrimitiveData();
  1466. this.setup();
  1467. }
  1468. configure(args) {
  1469. super.configure();
  1470. this.config.xAxisMode = args.xAxisMode;
  1471. this.config.yAxisMode = args.yAxisMode;
  1472. }
  1473. setPrimitiveData() {
  1474. // Define data and stuff
  1475. this.setObservers();
  1476. }
  1477. setObservers() {
  1478. // go through each component and check the keys in this.state it depends on
  1479. // set an observe() on each of those keys for that component
  1480. }
  1481. setHorizontalMargin() {
  1482. this.translateXLeft = Y_AXIS_MARGIN;
  1483. this.translateXRight = Y_AXIS_MARGIN;
  1484. }
  1485. checkData(data) {
  1486. return true;
  1487. }
  1488. setupConstants() {
  1489. this.state = {
  1490. xAxisLabels: [],
  1491. xAxisPositions: [],
  1492. xAxisMode: this.config.xAxisMode,
  1493. yAxisMode: this.config.yAxisMode
  1494. };
  1495. this.data.datasets.map(d => {
  1496. if(!d.chartType ) {
  1497. d.chartType = this.type;
  1498. }
  1499. });
  1500. // Prepare Y Axis
  1501. this.state.yAxis = {
  1502. labels: [],
  1503. positions: []
  1504. };
  1505. }
  1506. prepareData(data) {
  1507. let s = this.state;
  1508. s.xAxisLabels = data.labels || [];
  1509. s.datasetLength = s.xAxisLabels.length;
  1510. let zeroArray = new Array(s.datasetLength).fill(0);
  1511. s.datasets = data.datasets; // whole dataset info too
  1512. if(!data.datasets) {
  1513. // default
  1514. s.datasets = [{
  1515. values: zeroArray // Proof that state version will be seen instead of this.data
  1516. }];
  1517. }
  1518. s.datasets.map((d, i)=> {
  1519. let vals = d.values;
  1520. if(!vals) {
  1521. vals = zeroArray;
  1522. } else {
  1523. // Check for non values
  1524. vals = vals.map(val => (!isNaN(val) ? val : 0));
  1525. // Trim or extend
  1526. if(vals.length > s.datasetLength) {
  1527. vals = vals.slice(0, s.datasetLength);
  1528. } else {
  1529. vals = fillArray(vals, s.datasetLength - vals.length, 0);
  1530. }
  1531. }
  1532. d.index = i;
  1533. });
  1534. s.noOfDatasets = s.datasets.length;
  1535. s.yMarkers = data.yMarkers;
  1536. s.yRegions = data.yRegions;
  1537. }
  1538. calc() {
  1539. let s = this.state;
  1540. s.xAxisLabels = this.data.labels;
  1541. this.calcXPositions();
  1542. s.datasetsLabels = this.data.datasets.map(d => d.name);
  1543. this.setYAxis();
  1544. this.calcYUnits();
  1545. this.calcYMaximums();
  1546. this.calcYRegions();
  1547. }
  1548. setYAxis() {
  1549. this.calcYAxisParameters(this.state.yAxis, this.getAllYValues(), this.type === 'line');
  1550. this.state.zeroLine = this.state.yAxis.zeroLine;
  1551. }
  1552. calcXPositions() {
  1553. let s = this.state;
  1554. this.setUnitWidthAndXOffset();
  1555. s.xAxisPositions = s.xAxisLabels.map((d, i) =>
  1556. floatTwo(s.xOffset + i * s.unitWidth)
  1557. );
  1558. s.xUnitPositions = new Array(s.noOfDatasets).fill(s.xAxisPositions);
  1559. }
  1560. calcYAxisParameters(yAxis, dataValues, withMinimum = 'false') {
  1561. yAxis.labels = calcChartIntervals(dataValues, withMinimum);
  1562. const yPts = yAxis.labels;
  1563. yAxis.scaleMultiplier = this.height / getValueRange(yPts);
  1564. const intervalHeight = getIntervalSize(yPts) * yAxis.scaleMultiplier;
  1565. yAxis.zeroLine = this.height - (getZeroIndex(yPts) * intervalHeight);
  1566. yAxis.positions = yPts.map(d => yAxis.zeroLine - d * yAxis.scaleMultiplier);
  1567. }
  1568. calcYUnits() {
  1569. let s = this.state;
  1570. s.datasets.map(d => {
  1571. d.positions = d.values.map(val =>
  1572. floatTwo(s.yAxis.zeroLine - val * s.yAxis.scaleMultiplier));
  1573. });
  1574. if(this.barOptions && this.barOptions.stacked) {
  1575. s.datasets.map((d, i) => {
  1576. d.cumulativePositions = d.cumulativeYs.map(val =>
  1577. floatTwo(s.yAxis.zeroLine - val * s.yAxis.scaleMultiplier));
  1578. });
  1579. }
  1580. }
  1581. calcYMaximums() {
  1582. let s = this.state;
  1583. if(this.barOptions && this.barOptions.stacked) {
  1584. s.yExtremes = s.datasets[s.datasets.length - 1].cumulativePositions;
  1585. return;
  1586. }
  1587. s.yExtremes = new Array(s.datasetLength).fill(9999);
  1588. s.datasets.map((d, i) => {
  1589. d.positions.map((pos, j) => {
  1590. if(pos < s.yExtremes[j]) {
  1591. s.yExtremes[j] = pos;
  1592. }
  1593. });
  1594. });
  1595. // Tooltip refresh should not be needed?
  1596. // this.chartWrapper.removeChild(this.tip.container);
  1597. // this.make_tooltip();
  1598. }
  1599. calcYRegions() {
  1600. let s = this.state;
  1601. if(s.yMarkers) {
  1602. s.yMarkers = s.yMarkers.map(d => {
  1603. d.position = floatTwo(s.yAxis.zeroLine - d.value * s.yAxis.scaleMultiplier);
  1604. d.label += ': ' + d.value;
  1605. return d;
  1606. });
  1607. }
  1608. if(s.yRegions) {
  1609. s.yRegions = s.yRegions.map(d => {
  1610. if(d.end < d.start) {
  1611. [d.start, d.end] = [d.end, start];
  1612. }
  1613. d.start = floatTwo(s.yAxis.zeroLine - d.start * s.yAxis.scaleMultiplier);
  1614. d.end = floatTwo(s.yAxis.zeroLine - d.end * s.yAxis.scaleMultiplier);
  1615. return d;
  1616. });
  1617. }
  1618. }
  1619. // Default, as per bar, and mixed. Only line will be a special case
  1620. setUnitWidthAndXOffset() {
  1621. this.state.unitWidth = this.width/(this.state.datasetLength);
  1622. this.state.xOffset = this.state.unitWidth/2;
  1623. }
  1624. getAllYValues() {
  1625. // TODO: yMarkers, regions, sums, every Y value ever
  1626. let key = 'values';
  1627. if(this.barOptions && this.barOptions.stacked) {
  1628. key = 'cumulativeYs';
  1629. let cumulative = new Array(this.state.datasetLength).fill(0);
  1630. this.state.datasets.map((d, i) => {
  1631. let values = this.state.datasets[i].values;
  1632. d[key] = cumulative = cumulative.map((c, i) => c + values[i]);
  1633. });
  1634. }
  1635. return [].concat(...this.state.datasets.map(d => d[key]));
  1636. }
  1637. initComponents() {
  1638. this.componentConfigs = [
  1639. [
  1640. 'yAxis',
  1641. this.drawArea,
  1642. {
  1643. mode: this.yAxisMode,
  1644. width: this.width,
  1645. // pos: 'right'
  1646. },
  1647. {
  1648. positions: getRealIntervals(this.height, 4, 0, 0),
  1649. labels: getRealIntervals(this.height, 4, 0, 0).map(d => d + ""),
  1650. },
  1651. function() {
  1652. let s = this.state;
  1653. return {
  1654. positions: s.yAxis.positions,
  1655. labels: s.yAxis.labels,
  1656. }
  1657. }.bind(this)
  1658. ],
  1659. [
  1660. 'xAxis',
  1661. this.drawArea,
  1662. {
  1663. mode: this.xAxisMode,
  1664. height: this.height,
  1665. // pos: 'right'
  1666. },
  1667. {
  1668. positions: getRealIntervals(this.width, 4, 0, 1),
  1669. labels: getRealIntervals(this.width, 4, 0, 1).map(d => d + ""),
  1670. },
  1671. function() {
  1672. let s = this.state;
  1673. return {
  1674. positions: s.xAxisPositions,
  1675. labels: s.xAxisLabels,
  1676. }
  1677. }.bind(this)
  1678. ],
  1679. [
  1680. 'yRegions',
  1681. this.drawArea,
  1682. {
  1683. // mode: this.yAxisMode,
  1684. width: this.width,
  1685. pos: 'right'
  1686. },
  1687. [
  1688. {
  1689. start: this.height,
  1690. end: this.height,
  1691. label: ''
  1692. }
  1693. ],
  1694. function() {
  1695. return this.state.yRegions || [];
  1696. }.bind(this)
  1697. ],
  1698. [
  1699. 'yMarkers',
  1700. this.drawArea,
  1701. {
  1702. // mode: this.yAxisMode,
  1703. width: this.width,
  1704. pos: 'right'
  1705. },
  1706. [
  1707. {
  1708. position: this.height,
  1709. label: ''
  1710. }
  1711. ],
  1712. function() {
  1713. return this.state.yMarkers || [];
  1714. }.bind(this)
  1715. ]
  1716. ];
  1717. }
  1718. setupComponents() {
  1719. let optionals = ['yMarkers', 'yRegions'];
  1720. this.components = this.componentConfigs
  1721. .filter(args => !optionals.includes(args[0]) || this.data[args[0]])
  1722. .map(args => getComponent(...args));
  1723. }
  1724. getChartComponents() {
  1725. let dataUnitsComponents = [];
  1726. // this.state is not defined at this stage
  1727. this.data.datasets.forEach((d, index) => {
  1728. if(d.chartType === 'line') {
  1729. dataUnitsComponents.push(this.getPathComponent(d, index));
  1730. }
  1731. let renderer = this.unitRenderers[d.chartType];
  1732. dataUnitsComponents.push(this.getDataUnitComponent(
  1733. index, renderer
  1734. ));
  1735. });
  1736. return dataUnitsComponents;
  1737. }
  1738. getDataUnitComponent(index, unitRenderer) {
  1739. return new ChartComponent({
  1740. layerClass: 'dataset-units dataset-' + index,
  1741. makeElements: () => {
  1742. // yPositions, xPostions, color, valuesOverPoints,
  1743. let d = this.state.datasets[index];
  1744. return d.positions.map((y, j) => {
  1745. return unitRenderer.draw(
  1746. this.state.xAxisPositions[j],
  1747. y,
  1748. this.colors[index],
  1749. (this.valuesOverPoints ? (this.barOptions &&
  1750. this.barOptions.stacked ? d.cumulativeYs[j] : d.values[j]) : ''),
  1751. j,
  1752. y - (d.cumulativePositions ? d.cumulativePositions[j] : y)
  1753. );
  1754. });
  1755. },
  1756. postMake: function() {
  1757. let translate_layer = () => {
  1758. this.layer.setAttribute('transform', `translate(${unitRenderer.consts.width * index}, 0)`);
  1759. };
  1760. // let d = this.state.datasets[index];
  1761. if(this.meta.type === 'bar' && (!this.meta.barOptions
  1762. || !this.meta.barOptions.stacked)) {
  1763. translate_layer();
  1764. }
  1765. },
  1766. animate: (svgUnits) => {
  1767. // have been updated in axis render;
  1768. let newX = this.state.xAxisPositions;
  1769. let newY = this.state.datasets[index].positions;
  1770. let lastUnit = svgUnits[svgUnits.length - 1];
  1771. let parentNode = lastUnit.parentNode;
  1772. if(this.oldState.xExtra > 0) {
  1773. for(var i = 0; i<this.oldState.xExtra; i++) {
  1774. let unit = lastUnit.cloneNode(true);
  1775. parentNode.appendChild(unit);
  1776. svgUnits.push(unit);
  1777. }
  1778. }
  1779. svgUnits.map((unit, i) => {
  1780. if(newX[i] === undefined || newY[i] === undefined) return;
  1781. this.elementsToAnimate.push(unitRenderer.animate(
  1782. unit, // unit, with info to replace where it came from in the data
  1783. newX[i],
  1784. newY[i],
  1785. index,
  1786. this.state.noOfDatasets
  1787. ));
  1788. });
  1789. }
  1790. });
  1791. }
  1792. getPathComponent(d, index) {
  1793. return new ChartComponent({
  1794. layerClass: 'path dataset-path',
  1795. setData: () => {},
  1796. makeElements: () => {
  1797. let d = this.state.datasets[index];
  1798. let color = this.colors[index];
  1799. return getPaths(
  1800. d.positions,
  1801. this.state.xAxisPositions,
  1802. color,
  1803. this.config.heatline,
  1804. this.config.regionFill
  1805. );
  1806. },
  1807. animate: (paths) => {
  1808. let newX = this.state.xAxisPositions;
  1809. let newY = this.state.datasets[index].positions;
  1810. let oldX = this.oldState.xAxisPositions;
  1811. let oldY = this.oldState.datasets[index].positions;
  1812. let parentNode = paths[0].parentNode;
  1813. [oldX, newX] = equilizeNoOfElements(oldX, newX);
  1814. [oldY, newY] = equilizeNoOfElements(oldY, newY);
  1815. if(this.oldState.xExtra > 0) {
  1816. paths = getPaths(
  1817. oldY, oldX, this.colors[index],
  1818. this.config.heatline,
  1819. this.config.regionFill
  1820. );
  1821. parentNode.textContent = '';
  1822. paths.map(path => parentNode.appendChild(path));
  1823. }
  1824. const newPointsList = newY.map((y, i) => (newX[i] + ',' + y));
  1825. this.elementsToAnimate = this.elementsToAnimate
  1826. .concat(this.renderer.animatepath(paths, newPointsList.join("L")));
  1827. }
  1828. });
  1829. }
  1830. bindTooltip() {
  1831. // TODO: could be in tooltip itself, as it is a given functionality for its parent
  1832. this.chartWrapper.addEventListener('mousemove', (e) => {
  1833. let o = getOffset(this.chartWrapper);
  1834. let relX = e.pageX - o.left - this.translateXLeft;
  1835. let relY = e.pageY - o.top - this.translateY;
  1836. if(relY < this.height + this.translateY * 2) {
  1837. this.mapTooltipXPosition(relX);
  1838. } else {
  1839. this.tip.hide_tip();
  1840. }
  1841. });
  1842. }
  1843. mapTooltipXPosition(relX) {
  1844. let s = this.state;
  1845. if(!s.yExtremes) return;
  1846. let titles = s.xAxisLabels;
  1847. if(this.formatTooltipX && this.formatTooltipX(titles[0])) {
  1848. titles = titles.map(d=>this.formatTooltipX(d));
  1849. }
  1850. let formatY = this.formatTooltipY && this.formatTooltipY(this.y[0].values[0]);
  1851. for(var i=s.datasetLength - 1; i >= 0 ; i--) {
  1852. let xVal = s.xAxisPositions[i];
  1853. // let delta = i === 0 ? s.unitWidth : xVal - s.xAxisPositions[i-1];
  1854. if(relX > xVal - s.unitWidth/2) {
  1855. let x = xVal + this.translateXLeft;
  1856. let y = s.yExtremes[i] + this.translateY;
  1857. let values = s.datasets.map((set, j) => {
  1858. return {
  1859. title: set.title,
  1860. value: formatY ? this.formatTooltipY(set.values[i]) : set.values[i],
  1861. color: this.colors[j],
  1862. };
  1863. });
  1864. this.tip.set_values(x, y, titles[i], '', values);
  1865. this.tip.show_tip();
  1866. break;
  1867. }
  1868. }
  1869. }
  1870. getDataPoint(index=this.current_index) {
  1871. // check for length
  1872. let data_point = {
  1873. index: index
  1874. };
  1875. let y = this.y[0];
  1876. ['svg_units', 'yUnitPositions', 'values'].map(key => {
  1877. let data_key = key.slice(0, key.length-1);
  1878. data_point[data_key] = y[key][index];
  1879. });
  1880. data_point.label = this.xAxisLabels[index];
  1881. return data_point;
  1882. }
  1883. setCurrentDataPoint(index) {
  1884. index = parseInt(index);
  1885. if(index < 0) index = 0;
  1886. if(index >= this.xAxisLabels.length) index = this.xAxisLabels.length - 1;
  1887. if(index === this.current_index) return;
  1888. this.current_index = index;
  1889. $.fire(this.parent, "data-select", this.getDataPoint());
  1890. }
  1891. // API
  1892. addDataPoint(label, datasetValues, index=this.state.datasetLength) {
  1893. super.addDataPoint(label, datasetValues, index);
  1894. // console.log(label, datasetValues, this.data.labels);
  1895. this.data.labels.splice(index, 0, label);
  1896. this.data.datasets.map((d, i) => {
  1897. d.values.splice(index, 0, datasetValues[i]);
  1898. });
  1899. // console.log(this.data);
  1900. this.update(this.data);
  1901. }
  1902. removeDataPoint(index = this.state.datasetLength-1) {
  1903. super.removeDataPoint(index);
  1904. this.data.labels.splice(index, 1);
  1905. this.data.datasets.map(d => {
  1906. d.values.splice(index, 1);
  1907. });
  1908. this.update(this.data);
  1909. }
  1910. // updateData() {
  1911. // // animate if same no. of datasets,
  1912. // // else return new chart
  1913. // //
  1914. // }
  1915. }
  1916. // keep a binding at the end of chart
  1917. class LineChart extends AxisChart {
  1918. constructor(args) {
  1919. super(args);
  1920. this.type = 'line';
  1921. if(Object.getPrototypeOf(this) !== LineChart.prototype) {
  1922. return;
  1923. }
  1924. this.setup();
  1925. }
  1926. configure(args) {
  1927. super.configure(args);
  1928. this.config.xAxisMode = args.xAxisMode || 'span';
  1929. this.config.yAxisMode = args.yAxisMode || 'span';
  1930. this.config.dotRadius = args.dotRadius || 4;
  1931. this.config.heatline = args.heatline || 0;
  1932. this.config.regionFill = args.regionFill || 0;
  1933. this.config.showDots = args.showDots || 1;
  1934. }
  1935. configUnits() {
  1936. this.unitArgs = {
  1937. type: 'dot',
  1938. args: { radius: this.config.dotRadius }
  1939. };
  1940. }
  1941. // temp commented
  1942. setUnitWidthAndXOffset() {
  1943. this.state.unitWidth = this.width/(this.state.datasetLength - 1);
  1944. this.state.xOffset = 0;
  1945. }
  1946. }
  1947. class ScatterChart extends LineChart {
  1948. constructor(args) {
  1949. super(args);
  1950. this.type = 'scatter';
  1951. if(!args.dotRadius) {
  1952. this.dotRadius = 8;
  1953. } else {
  1954. this.dotRadius = args.dotRadius;
  1955. }
  1956. this.setup();
  1957. }
  1958. setup_values() {
  1959. super.setup_values();
  1960. this.unit_args = {
  1961. type: 'dot',
  1962. args: { radius: this.dotRadius }
  1963. };
  1964. }
  1965. make_paths() {}
  1966. make_path() {}
  1967. }
  1968. class MultiAxisChart extends AxisChart {
  1969. constructor(args) {
  1970. super(args);
  1971. // this.unitType = args.unitType || 'line';
  1972. // this.setup();
  1973. }
  1974. preSetup() {
  1975. this.type = 'multiaxis';
  1976. }
  1977. setHorizontalMargin() {
  1978. let noOfLeftAxes = this.data.datasets.filter(d => d.axisPosition === 'left').length;
  1979. this.translateXLeft = (noOfLeftAxes) * Y_AXIS_MARGIN || Y_AXIS_MARGIN;
  1980. this.translateXRight = (this.data.datasets.length - noOfLeftAxes) * Y_AXIS_MARGIN || Y_AXIS_MARGIN;
  1981. }
  1982. prepareYAxis() { }
  1983. prepareData(data) {
  1984. super.prepareData(data);
  1985. let sets = this.state.datasets;
  1986. // let axesLeft = sets.filter(d => d.axisPosition === 'left');
  1987. // let axesRight = sets.filter(d => d.axisPosition === 'right');
  1988. // let axesNone = sets.filter(d => !d.axisPosition ||
  1989. // !['left', 'right'].includes(d.axisPosition));
  1990. let leftCount = 0, rightCount = 0;
  1991. sets.forEach((d, i) => {
  1992. d.yAxis = {
  1993. position: d.axisPosition,
  1994. index: d.axisPosition === 'left' ? leftCount++ : rightCount++
  1995. };
  1996. });
  1997. }
  1998. configure(args) {
  1999. super.configure(args);
  2000. this.config.xAxisMode = args.xAxisMode || 'tick';
  2001. this.config.yAxisMode = args.yAxisMode || 'span';
  2002. }
  2003. // setUnitWidthAndXOffset() {
  2004. // this.state.unitWidth = this.width/(this.state.datasetLength);
  2005. // this.state.xOffset = this.state.unitWidth/2;
  2006. // }
  2007. configUnits() {
  2008. this.unitArgs = {
  2009. type: 'bar',
  2010. args: {
  2011. spaceWidth: this.state.unitWidth/2,
  2012. }
  2013. };
  2014. }
  2015. setYAxis() {
  2016. this.state.datasets.map(d => {
  2017. this.calcYAxisParameters(d.yAxis, d.values, this.unitType === 'line');
  2018. });
  2019. }
  2020. calcYUnits() {
  2021. this.state.datasets.map(d => {
  2022. d.positions = d.values.map(val => floatTwo(d.yAxis.zeroLine - val * d.yAxis.scaleMultiplier));
  2023. });
  2024. }
  2025. renderConstants() {
  2026. this.state.datasets.map(d => {
  2027. let guidePos = d.yAxis.position === 'left'
  2028. ? -1 * d.yAxis.index * Y_AXIS_MARGIN
  2029. : this.width + d.yAxis.index * Y_AXIS_MARGIN;
  2030. this.renderer.xLine(guidePos, '', {
  2031. pos:'top',
  2032. mode: 'span',
  2033. stroke: this.colors[i],
  2034. className: 'y-axis-guide'
  2035. });
  2036. });
  2037. }
  2038. getYAxesComponents() {
  2039. return this.data.datasets.map((e, i) => {
  2040. return new ChartComponent({
  2041. layerClass: 'y axis y-axis-' + i,
  2042. make: () => {
  2043. let yAxis = this.state.datasets[i].yAxis;
  2044. this.renderer.setZeroline(yAxis.zeroline);
  2045. let options = {
  2046. pos: yAxis.position,
  2047. mode: 'tick',
  2048. offset: yAxis.index * Y_AXIS_MARGIN,
  2049. stroke: this.colors[i]
  2050. };
  2051. return yAxis.positions.map((position, j) =>
  2052. this.renderer.yLine(position, yAxis.labels[j], options)
  2053. );
  2054. },
  2055. animate: () => {}
  2056. });
  2057. });
  2058. }
  2059. // TODO remove renderer zeroline from above and below
  2060. getChartComponents() {
  2061. return this.data.datasets.map((d, index) => {
  2062. return new ChartComponent({
  2063. layerClass: 'dataset-units dataset-' + index,
  2064. make: () => {
  2065. let d = this.state.datasets[index];
  2066. let unitType = this.unitArgs;
  2067. // the only difference, should be tied to datasets or default
  2068. this.renderer.setZeroline(d.yAxis.zeroLine);
  2069. return d.positions.map((y, j) => {
  2070. return this.renderer[unitType.type](
  2071. this.state.xAxisPositions[j],
  2072. y,
  2073. unitType.args,
  2074. this.colors[index],
  2075. j,
  2076. index,
  2077. this.state.datasetLength
  2078. );
  2079. });
  2080. },
  2081. animate: (svgUnits) => {
  2082. let d = this.state.datasets[index];
  2083. let unitType = this.unitArgs.type;
  2084. // have been updated in axis render;
  2085. let newX = this.state.xAxisPositions;
  2086. let newY = this.state.datasets[index].positions;
  2087. let lastUnit = svgUnits[svgUnits.length - 1];
  2088. let parentNode = lastUnit.parentNode;
  2089. if(this.oldState.xExtra > 0) {
  2090. for(var i = 0; i<this.oldState.xExtra; i++) {
  2091. let unit = lastUnit.cloneNode(true);
  2092. parentNode.appendChild(unit);
  2093. svgUnits.push(unit);
  2094. }
  2095. }
  2096. this.renderer.setZeroline(d.yAxis.zeroLine);
  2097. svgUnits.map((unit, i) => {
  2098. if(newX[i] === undefined || newY[i] === undefined) return;
  2099. this.elementsToAnimate.push(this.renderer['animate' + unitType](
  2100. unit, // unit, with info to replace where it came from in the data
  2101. newX[i],
  2102. newY[i],
  2103. index,
  2104. this.state.noOfDatasets
  2105. ));
  2106. });
  2107. }
  2108. });
  2109. });
  2110. }
  2111. }
  2112. class PercentageChart extends BaseChart {
  2113. constructor(args) {
  2114. super(args);
  2115. this.type = 'percentage';
  2116. this.max_slices = 10;
  2117. this.max_legend_points = 6;
  2118. this.setup();
  2119. }
  2120. makeChartArea() {
  2121. this.chartWrapper.className += ' ' + 'graph-focus-margin';
  2122. this.chartWrapper.style.marginTop = '45px';
  2123. this.statsWrapper.className += ' ' + 'graph-focus-margin';
  2124. this.statsWrapper.style.marginBottom = '30px';
  2125. this.statsWrapper.style.paddingTop = '0px';
  2126. this.chartDiv = $$1.create('div', {
  2127. className: 'div',
  2128. inside: this.chartWrapper
  2129. });
  2130. this.chart = $$1.create('div', {
  2131. className: 'progress-chart',
  2132. inside: this.chartDiv
  2133. });
  2134. }
  2135. setupLayers() {
  2136. this.percentageBar = $$1.create('div', {
  2137. className: 'progress',
  2138. inside: this.chart
  2139. });
  2140. }
  2141. setup_values() {
  2142. this.slice_totals = [];
  2143. let all_totals = this.data.labels.map((d, i) => {
  2144. let total = 0;
  2145. this.data.datasets.map(e => {
  2146. total += e.values[i];
  2147. });
  2148. return [total, d];
  2149. }).filter(d => { return d[0] > 0; }); // keep only positive results
  2150. let totals = all_totals;
  2151. if(all_totals.length > this.max_slices) {
  2152. all_totals.sort((a, b) => { return b[0] - a[0]; });
  2153. totals = all_totals.slice(0, this.max_slices-1);
  2154. let others = all_totals.slice(this.max_slices-1);
  2155. let sum_of_others = 0;
  2156. others.map(d => {sum_of_others += d[0];});
  2157. totals.push([sum_of_others, 'Rest']);
  2158. this.colors[this.max_slices-1] = 'grey';
  2159. }
  2160. this.labels = [];
  2161. totals.map(d => {
  2162. this.slice_totals.push(d[0]);
  2163. this.labels.push(d[1]);
  2164. });
  2165. this.legend_totals = this.slice_totals.slice(0, this.max_legend_points);
  2166. }
  2167. renderComponents() {
  2168. this.grand_total = this.slice_totals.reduce((a, b) => a + b, 0);
  2169. this.slices = [];
  2170. this.slice_totals.map((total, i) => {
  2171. let slice = $$1.create('div', {
  2172. className: `progress-bar`,
  2173. inside: this.percentageBar,
  2174. styles: {
  2175. background: this.colors[i],
  2176. width: total*100/this.grand_total + "%"
  2177. }
  2178. });
  2179. this.slices.push(slice);
  2180. });
  2181. }
  2182. calc() {}
  2183. bindTooltip() {
  2184. this.slices.map((slice, i) => {
  2185. slice.addEventListener('mouseenter', () => {
  2186. let g_off = getOffset(this.chartWrapper), p_off = getOffset(slice);
  2187. let x = p_off.left - g_off.left + slice.offsetWidth/2;
  2188. let y = p_off.top - g_off.top - 6;
  2189. let title = (this.formatted_labels && this.formatted_labels.length>0
  2190. ? this.formatted_labels[i] : this.labels[i]) + ': ';
  2191. let percent = (this.slice_totals[i]*100/this.grand_total).toFixed(1);
  2192. this.tip.set_values(x, y, title, percent + "%");
  2193. this.tip.show_tip();
  2194. });
  2195. });
  2196. }
  2197. renderLegend() {
  2198. let x_values = this.formatted_labels && this.formatted_labels.length > 0
  2199. ? this.formatted_labels : this.labels;
  2200. this.legend_totals.map((d, i) => {
  2201. if(d) {
  2202. let stats = $$1.create('div', {
  2203. className: 'stats',
  2204. inside: this.statsWrapper
  2205. });
  2206. stats.innerHTML = `<span class="indicator">
  2207. <i style="background: ${this.colors[i]}"></i>
  2208. <span class="text-muted">${x_values[i]}:</span>
  2209. ${d}
  2210. </span>`;
  2211. }
  2212. });
  2213. }
  2214. }
  2215. const ANGLE_RATIO = Math.PI / 180;
  2216. const FULL_ANGLE = 360;
  2217. class PieChart extends BaseChart {
  2218. constructor(args) {
  2219. super(args);
  2220. this.type = 'pie';
  2221. this.elements_to_animate = null;
  2222. this.hoverRadio = args.hoverRadio || 0.1;
  2223. this.max_slices = 10;
  2224. this.max_legend_points = 6;
  2225. this.isAnimate = false;
  2226. this.startAngle = args.startAngle || 0;
  2227. this.clockWise = args.clockWise || false;
  2228. this.mouseMove = this.mouseMove.bind(this);
  2229. this.mouseLeave = this.mouseLeave.bind(this);
  2230. this.setup();
  2231. }
  2232. setup_values() {
  2233. this.centerX = this.width / 2;
  2234. this.centerY = this.height / 2;
  2235. this.radius = (this.height > this.width ? this.centerX : this.centerY);
  2236. this.slice_totals = [];
  2237. let all_totals = this.data.labels.map((d, i) => {
  2238. let total = 0;
  2239. this.data.datasets.map(e => {
  2240. total += e.values[i];
  2241. });
  2242. return [total, d];
  2243. }).filter(d => { return d[0] > 0; }); // keep only positive results
  2244. let totals = all_totals;
  2245. if(all_totals.length > this.max_slices) {
  2246. all_totals.sort((a, b) => { return b[0] - a[0]; });
  2247. totals = all_totals.slice(0, this.max_slices-1);
  2248. let others = all_totals.slice(this.max_slices-1);
  2249. let sum_of_others = 0;
  2250. others.map(d => {sum_of_others += d[0];});
  2251. totals.push([sum_of_others, 'Rest']);
  2252. this.colors[this.max_slices-1] = 'grey';
  2253. }
  2254. this.labels = [];
  2255. totals.map(d => {
  2256. this.slice_totals.push(d[0]);
  2257. this.labels.push(d[1]);
  2258. });
  2259. this.legend_totals = this.slice_totals.slice(0, this.max_legend_points);
  2260. }
  2261. static getPositionByAngle(angle,radius){
  2262. return {
  2263. x:Math.sin(angle * ANGLE_RATIO) * radius,
  2264. y:Math.cos(angle * ANGLE_RATIO) * radius,
  2265. };
  2266. }
  2267. makeArcPath(startPosition,endPosition){
  2268. const{centerX,centerY,radius,clockWise} = this;
  2269. 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`;
  2270. }
  2271. renderComponents(init){
  2272. const{radius,clockWise} = this;
  2273. this.grand_total = this.slice_totals.reduce((a, b) => a + b, 0);
  2274. const prevSlicesProperties = this.slicesProperties || [];
  2275. this.slices = [];
  2276. this.elements_to_animate = [];
  2277. this.slicesProperties = [];
  2278. let curAngle = 180 - this.startAngle;
  2279. this.slice_totals.map((total, i) => {
  2280. const startAngle = curAngle;
  2281. const originDiffAngle = (total / this.grand_total) * FULL_ANGLE;
  2282. const diffAngle = clockWise ? -originDiffAngle : originDiffAngle;
  2283. const endAngle = curAngle = curAngle + diffAngle;
  2284. const startPosition = PieChart.getPositionByAngle(startAngle,radius);
  2285. const endPosition = PieChart.getPositionByAngle(endAngle,radius);
  2286. const prevProperty = init && prevSlicesProperties[i];
  2287. let curStart,curEnd;
  2288. if(init){
  2289. curStart = prevProperty?prevProperty.startPosition : startPosition;
  2290. curEnd = prevProperty? prevProperty.endPosition : startPosition;
  2291. }else{
  2292. curStart = startPosition;
  2293. curEnd = endPosition;
  2294. }
  2295. const curPath = this.makeArcPath(curStart,curEnd);
  2296. let slice = makePath(curPath, 'pie-path', 'none', this.colors[i]);
  2297. slice.style.transition = 'transform .3s;';
  2298. this.drawArea.appendChild(slice);
  2299. this.slices.push(slice);
  2300. this.slicesProperties.push({
  2301. startPosition,
  2302. endPosition,
  2303. value: total,
  2304. total: this.grand_total,
  2305. startAngle,
  2306. endAngle,
  2307. angle:diffAngle
  2308. });
  2309. if(init){
  2310. this.elements_to_animate.push([{unit: slice, array: this.slices, index: this.slices.length - 1},
  2311. {d:this.makeArcPath(startPosition,endPosition)},
  2312. 650, "easein",null,{
  2313. d:curPath
  2314. }]);
  2315. }
  2316. });
  2317. if(init){
  2318. runSMILAnimation(this.chartWrapper, this.svg, this.elements_to_animate);
  2319. }
  2320. }
  2321. calTranslateByAngle(property){
  2322. const{radius,hoverRadio} = this;
  2323. const position = PieChart.getPositionByAngle(property.startAngle+(property.angle / 2),radius);
  2324. return `translate3d(${(position.x) * hoverRadio}px,${(position.y) * hoverRadio}px,0)`;
  2325. }
  2326. hoverSlice(path,i,flag,e){
  2327. if(!path) return;
  2328. const color = this.colors[i];
  2329. if(flag){
  2330. transform(path,this.calTranslateByAngle(this.slicesProperties[i]));
  2331. path.style.fill = lightenDarkenColor(color,50);
  2332. let g_off = getOffset(this.svg);
  2333. let x = e.pageX - g_off.left + 10;
  2334. let y = e.pageY - g_off.top - 10;
  2335. let title = (this.formatted_labels && this.formatted_labels.length>0
  2336. ? this.formatted_labels[i] : this.labels[i]) + ': ';
  2337. let percent = (this.slice_totals[i]*100/this.grand_total).toFixed(1);
  2338. this.tip.set_values(x, y, title, percent + "%");
  2339. this.tip.show_tip();
  2340. }else{
  2341. transform(path,'translate3d(0,0,0)');
  2342. this.tip.hide_tip();
  2343. path.style.fill = color;
  2344. }
  2345. }
  2346. mouseMove(e){
  2347. const target = e.target;
  2348. let prevIndex = this.curActiveSliceIndex;
  2349. let prevAcitve = this.curActiveSlice;
  2350. for(let i = 0; i < this.slices.length; i++){
  2351. if(target === this.slices[i]){
  2352. this.hoverSlice(prevAcitve,prevIndex,false);
  2353. this.curActiveSlice = target;
  2354. this.curActiveSliceIndex = i;
  2355. this.hoverSlice(target,i,true,e);
  2356. break;
  2357. }
  2358. }
  2359. }
  2360. mouseLeave(){
  2361. this.hoverSlice(this.curActiveSlice,this.curActiveSliceIndex,false);
  2362. }
  2363. bindTooltip() {
  2364. this.drawArea.addEventListener('mousemove',this.mouseMove);
  2365. this.drawArea.addEventListener('mouseleave',this.mouseLeave);
  2366. }
  2367. renderLegend() {
  2368. let x_values = this.formatted_labels && this.formatted_labels.length > 0
  2369. ? this.formatted_labels : this.labels;
  2370. this.legend_totals.map((d, i) => {
  2371. const color = this.colors[i];
  2372. if(d) {
  2373. let stats = $$1.create('div', {
  2374. className: 'stats',
  2375. inside: this.statsWrapper
  2376. });
  2377. stats.innerHTML = `<span class="indicator">
  2378. <i style="background-color:${color};"></i>
  2379. <span class="text-muted">${x_values[i]}:</span>
  2380. ${d}
  2381. </span>`;
  2382. }
  2383. });
  2384. }
  2385. }
  2386. // Playing around with dates
  2387. // https://stackoverflow.com/a/11252167/6495043
  2388. function treatAsUtc(dateStr) {
  2389. let result = new Date(dateStr);
  2390. result.setMinutes(result.getMinutes() - result.getTimezoneOffset());
  2391. return result;
  2392. }
  2393. function getDdMmYyyy(date) {
  2394. let dd = date.getDate();
  2395. let mm = date.getMonth() + 1; // getMonth() is zero-based
  2396. return [
  2397. (dd>9 ? '' : '0') + dd,
  2398. (mm>9 ? '' : '0') + mm,
  2399. date.getFullYear()
  2400. ].join('-');
  2401. }
  2402. function getWeeksBetween(startDateStr, endDateStr) {
  2403. return Math.ceil(getDaysBetween(startDateStr, endDateStr) / 7);
  2404. }
  2405. function getDaysBetween(startDateStr, endDateStr) {
  2406. let millisecondsPerDay = 24 * 60 * 60 * 1000;
  2407. return (treatAsUtc(endDateStr) - treatAsUtc(startDateStr)) / millisecondsPerDay;
  2408. }
  2409. // mutates
  2410. function addDays(date, numberOfDays) {
  2411. date.setDate(date.getDate() + numberOfDays);
  2412. }
  2413. // export function getMonthName() {}
  2414. class Heatmap extends BaseChart {
  2415. constructor({
  2416. start = '',
  2417. domain = '',
  2418. subdomain = '',
  2419. data = {},
  2420. discrete_domains = 0,
  2421. count_label = '',
  2422. legend_colors = []
  2423. }) {
  2424. super(arguments[0]);
  2425. this.type = 'heatmap';
  2426. this.domain = domain;
  2427. this.subdomain = subdomain;
  2428. this.data = data;
  2429. this.discrete_domains = discrete_domains;
  2430. this.count_label = count_label;
  2431. let today = new Date();
  2432. this.start = start || addDays(today, 365);
  2433. legend_colors = legend_colors.slice(0, 5);
  2434. this.legend_colors = this.validate_colors(legend_colors)
  2435. ? legend_colors
  2436. : ['#ebedf0', '#c6e48b', '#7bc96f', '#239a3b', '#196127'];
  2437. // Fixed 5-color theme,
  2438. // More colors are difficult to parse visually
  2439. this.distribution_size = 5;
  2440. this.translateX = 0;
  2441. // this.setup();
  2442. }
  2443. validate_colors(colors) {
  2444. if(colors.length < 5) return 0;
  2445. let valid = 1;
  2446. colors.forEach(function(string) {
  2447. if(!isValidColor(string)) {
  2448. valid = 0;
  2449. console.warn('"' + string + '" is not a valid color.');
  2450. }
  2451. }, this);
  2452. return valid;
  2453. }
  2454. setupConstants() {
  2455. this.today = new Date();
  2456. if(!this.start) {
  2457. this.start = new Date();
  2458. this.start.setFullYear( this.start.getFullYear() - 1 );
  2459. }
  2460. this.first_week_start = new Date(this.start.toDateString());
  2461. this.last_week_start = new Date(this.today.toDateString());
  2462. if(this.first_week_start.getDay() !== 7) {
  2463. addDays(this.first_week_start, (-1) * this.first_week_start.getDay());
  2464. }
  2465. if(this.last_week_start.getDay() !== 7) {
  2466. addDays(this.last_week_start, (-1) * this.last_week_start.getDay());
  2467. }
  2468. this.no_of_cols = getWeeksBetween(this.first_week_start + '', this.last_week_start + '') + 1;
  2469. }
  2470. calcWidth() {
  2471. this.baseWidth = (this.no_of_cols + 3) * 12 ;
  2472. if(this.discrete_domains) {
  2473. this.baseWidth += (12 * 12);
  2474. }
  2475. }
  2476. setupLayers() {
  2477. this.domain_label_group = this.makeLayer(
  2478. 'domain-label-group chart-label');
  2479. this.data_groups = this.makeLayer(
  2480. 'data-groups',
  2481. `translate(0, 20)`
  2482. );
  2483. }
  2484. setup_values() {
  2485. this.domain_label_group.textContent = '';
  2486. this.data_groups.textContent = '';
  2487. let data_values = Object.keys(this.data).map(key => this.data[key]);
  2488. this.distribution = calcDistribution(data_values, this.distribution_size);
  2489. this.month_names = ["January", "February", "March", "April", "May", "June",
  2490. "July", "August", "September", "October", "November", "December"
  2491. ];
  2492. this.render_all_weeks_and_store_x_values(this.no_of_cols);
  2493. }
  2494. render_all_weeks_and_store_x_values(no_of_weeks) {
  2495. let current_week_sunday = new Date(this.first_week_start);
  2496. this.week_col = 0;
  2497. this.current_month = current_week_sunday.getMonth();
  2498. this.months = [this.current_month + ''];
  2499. this.month_weeks = {}, this.month_start_points = [];
  2500. this.month_weeks[this.current_month] = 0;
  2501. this.month_start_points.push(13);
  2502. for(var i = 0; i < no_of_weeks; i++) {
  2503. let data_group, month_change = 0;
  2504. let day = new Date(current_week_sunday);
  2505. [data_group, month_change] = this.get_week_squares_group(day, this.week_col);
  2506. this.data_groups.appendChild(data_group);
  2507. this.week_col += 1 + parseInt(this.discrete_domains && month_change);
  2508. this.month_weeks[this.current_month]++;
  2509. if(month_change) {
  2510. this.current_month = (this.current_month + 1) % 12;
  2511. this.months.push(this.current_month + '');
  2512. this.month_weeks[this.current_month] = 1;
  2513. }
  2514. addDays(current_week_sunday, 7);
  2515. }
  2516. this.render_month_labels();
  2517. }
  2518. get_week_squares_group(current_date, index) {
  2519. const no_of_weekdays = 7;
  2520. const square_side = 10;
  2521. const cell_padding = 2;
  2522. const step = 1;
  2523. const today_time = this.today.getTime();
  2524. let month_change = 0;
  2525. let week_col_change = 0;
  2526. let data_group = makeSVGGroup(this.data_groups, 'data-group');
  2527. for(var y = 0, i = 0; i < no_of_weekdays; i += step, y += (square_side + cell_padding)) {
  2528. let data_value = 0;
  2529. let color_index = 0;
  2530. let current_timestamp = current_date.getTime()/1000;
  2531. let timestamp = Math.floor(current_timestamp - (current_timestamp % 86400)).toFixed(1);
  2532. if(this.data[timestamp]) {
  2533. data_value = this.data[timestamp];
  2534. }
  2535. if(this.data[Math.round(timestamp)]) {
  2536. data_value = this.data[Math.round(timestamp)];
  2537. }
  2538. if(data_value) {
  2539. color_index = getMaxCheckpoint(data_value, this.distribution);
  2540. }
  2541. let x = 13 + (index + week_col_change) * 12;
  2542. let dataAttr = {
  2543. 'data-date': getDdMmYyyy(current_date),
  2544. 'data-value': data_value,
  2545. 'data-day': current_date.getDay()
  2546. };
  2547. let heatSquare = makeHeatSquare('day', x, y, square_side,
  2548. this.legend_colors[color_index], dataAttr);
  2549. data_group.appendChild(heatSquare);
  2550. let next_date = new Date(current_date);
  2551. addDays(next_date, 1);
  2552. if(next_date.getTime() > today_time) break;
  2553. if(next_date.getMonth() - current_date.getMonth()) {
  2554. month_change = 1;
  2555. if(this.discrete_domains) {
  2556. week_col_change = 1;
  2557. }
  2558. this.month_start_points.push(13 + (index + week_col_change) * 12);
  2559. }
  2560. current_date = next_date;
  2561. }
  2562. return [data_group, month_change];
  2563. }
  2564. render_month_labels() {
  2565. // this.first_month_label = 1;
  2566. // if (this.first_week_start.getDate() > 8) {
  2567. // this.first_month_label = 0;
  2568. // }
  2569. // this.last_month_label = 1;
  2570. // let first_month = this.months.shift();
  2571. // let first_month_start = this.month_start_points.shift();
  2572. // render first month if
  2573. // let last_month = this.months.pop();
  2574. // let last_month_start = this.month_start_points.pop();
  2575. // render last month if
  2576. this.months.shift();
  2577. this.month_start_points.shift();
  2578. this.months.pop();
  2579. this.month_start_points.pop();
  2580. this.month_start_points.map((start, i) => {
  2581. let month_name = this.month_names[this.months[i]].substring(0, 3);
  2582. let text = makeText('y-value-text', start+12, 10, month_name);
  2583. this.domain_label_group.appendChild(text);
  2584. });
  2585. }
  2586. renderComponents() {
  2587. Array.prototype.slice.call(
  2588. this.container.querySelectorAll('.graph-stats-container, .sub-title, .title')
  2589. ).map(d => {
  2590. d.style.display = 'None';
  2591. });
  2592. this.chartWrapper.style.marginTop = '0px';
  2593. this.chartWrapper.style.paddingTop = '0px';
  2594. }
  2595. bindTooltip() {
  2596. Array.prototype.slice.call(
  2597. document.querySelectorAll(".data-group .day")
  2598. ).map(el => {
  2599. el.addEventListener('mouseenter', (e) => {
  2600. let count = e.target.getAttribute('data-value');
  2601. let date_parts = e.target.getAttribute('data-date').split('-');
  2602. let month = this.month_names[parseInt(date_parts[1])-1].substring(0, 3);
  2603. let g_off = this.chartWrapper.getBoundingClientRect(), p_off = e.target.getBoundingClientRect();
  2604. let width = parseInt(e.target.getAttribute('width'));
  2605. let x = p_off.left - g_off.left + (width+2)/2;
  2606. let y = p_off.top - g_off.top - (width+2)/2;
  2607. let value = count + ' ' + this.count_label;
  2608. let name = ' on ' + month + ' ' + date_parts[0] + ', ' + date_parts[2];
  2609. this.tip.set_values(x, y, name, value, [], 1);
  2610. this.tip.show_tip();
  2611. });
  2612. });
  2613. }
  2614. update(data) {
  2615. this.data = data;
  2616. this.setup_values();
  2617. this.bindTooltip();
  2618. }
  2619. }
  2620. const chartTypes = {
  2621. mixed: AxisChart,
  2622. multiaxis: MultiAxisChart,
  2623. scatter: ScatterChart,
  2624. percentage: PercentageChart,
  2625. heatmap: Heatmap,
  2626. pie: PieChart
  2627. };
  2628. function getChartByType(chartType = 'line', options) {
  2629. debugger;
  2630. if(chartType === 'line') {
  2631. options.type = 'line';
  2632. return new AxisChart(options);
  2633. } else if (chartType === 'bar') {
  2634. options.type = 'bar';
  2635. return new AxisChart(options);
  2636. }
  2637. if (!chartTypes[chartType]) {
  2638. console.error("Undefined chart type: " + chartType);
  2639. return;
  2640. }
  2641. return new chartTypes[chartType](options);
  2642. }
  2643. class Chart {
  2644. constructor(args) {
  2645. return getChartByType(args.type, arguments[0]);
  2646. }
  2647. }
  2648. export default Chart;