25개 이상의 토픽을 선택하실 수 없습니다. Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

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