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.
 
 
 

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