Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.
 
 
 

2770 řádky
67 KiB

  1. function $(expr, con) {
  2. return typeof expr === "string"? (con || document).querySelector(expr) : expr || null;
  3. }
  4. $.create = (tag, o) => {
  5. var element = document.createElement(tag);
  6. for (var i in o) {
  7. var val = o[i];
  8. if (i === "inside") {
  9. $(val).appendChild(element);
  10. }
  11. else if (i === "around") {
  12. var ref = $(val);
  13. ref.parentNode.insertBefore(element, ref);
  14. element.appendChild(ref);
  15. } else if (i === "styles") {
  16. if(typeof val === "object") {
  17. Object.keys(val).map(prop => {
  18. element.style[prop] = val[prop];
  19. });
  20. }
  21. } else if (i in element ) {
  22. element[i] = val;
  23. }
  24. else {
  25. element.setAttribute(i, val);
  26. }
  27. }
  28. return element;
  29. };
  30. function getOffset(element) {
  31. let rect = element.getBoundingClientRect();
  32. return {
  33. // https://stackoverflow.com/a/7436602/6495043
  34. // rect.top varies with scroll, so we add whatever has been
  35. // scrolled to it to get absolute distance from actual page top
  36. top: rect.top + (document.documentElement.scrollTop || document.body.scrollTop),
  37. left: rect.left + (document.documentElement.scrollLeft || document.body.scrollLeft)
  38. };
  39. }
  40. function isElementInViewport(el) {
  41. // Although straightforward: https://stackoverflow.com/a/7557433/6495043
  42. var rect = el.getBoundingClientRect();
  43. return (
  44. rect.top >= 0 &&
  45. rect.left >= 0 &&
  46. rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) && /*or $(window).height() */
  47. rect.right <= (window.innerWidth || document.documentElement.clientWidth) /*or $(window).width() */
  48. );
  49. }
  50. function getElementContentWidth(element) {
  51. var styles = window.getComputedStyle(element);
  52. var padding = parseFloat(styles.paddingLeft) +
  53. parseFloat(styles.paddingRight);
  54. return element.clientWidth - padding;
  55. }
  56. function fire(target, type, properties) {
  57. var evt = document.createEvent("HTMLEvents");
  58. evt.initEvent(type, true, true );
  59. for (var j in properties) {
  60. evt[j] = properties[j];
  61. }
  62. return target.dispatchEvent(evt);
  63. }
  64. class SvgTip {
  65. constructor({
  66. parent = null,
  67. colors = []
  68. }) {
  69. this.parent = parent;
  70. this.colors = colors;
  71. this.title_name = '';
  72. this.title_value = '';
  73. this.list_values = [];
  74. this.title_value_first = 0;
  75. this.x = 0;
  76. this.y = 0;
  77. this.top = 0;
  78. this.left = 0;
  79. this.setup();
  80. }
  81. setup() {
  82. this.make_tooltip();
  83. }
  84. refresh() {
  85. this.fill();
  86. this.calc_position();
  87. // this.show_tip();
  88. }
  89. make_tooltip() {
  90. this.container = $.create('div', {
  91. inside: this.parent,
  92. className: 'graph-svg-tip comparison',
  93. innerHTML: `<span class="title"></span>
  94. <ul class="data-point-list"></ul>
  95. <div class="svg-pointer"></div>`
  96. });
  97. this.hide_tip();
  98. this.title = this.container.querySelector('.title');
  99. this.data_point_list = this.container.querySelector('.data-point-list');
  100. this.parent.addEventListener('mouseleave', () => {
  101. this.hide_tip();
  102. });
  103. }
  104. fill() {
  105. let title;
  106. if(this.title_value_first) {
  107. title = `<strong>${this.title_value}</strong>${this.title_name}`;
  108. } else {
  109. title = `${this.title_name}<strong>${this.title_value}</strong>`;
  110. }
  111. this.title.innerHTML = title;
  112. this.data_point_list.innerHTML = '';
  113. this.list_values.map((set, i) => {
  114. const color = this.colors[i] || 'black';
  115. let li = $.create('li', {
  116. styles: {
  117. 'border-top': `3px solid ${color}`
  118. },
  119. innerHTML: `<strong style="display: block;">${ set.value === 0 || set.value ? set.value : '' }</strong>
  120. ${set.title ? set.title : '' }`
  121. });
  122. this.data_point_list.appendChild(li);
  123. });
  124. }
  125. calc_position() {
  126. let width = this.container.offsetWidth;
  127. this.top = this.y - this.container.offsetHeight;
  128. this.left = this.x - width/2;
  129. let max_left = this.parent.offsetWidth - width;
  130. let pointer = this.container.querySelector('.svg-pointer');
  131. if(this.left < 0) {
  132. pointer.style.left = `calc(50% - ${-1 * this.left}px)`;
  133. this.left = 0;
  134. } else if(this.left > max_left) {
  135. let delta = this.left - max_left;
  136. let pointer_offset = `calc(50% + ${delta}px)`;
  137. pointer.style.left = pointer_offset;
  138. this.left = max_left;
  139. } else {
  140. pointer.style.left = `50%`;
  141. }
  142. }
  143. set_values(x, y, title_name = '', title_value = '', list_values = [], title_value_first = 0) {
  144. this.title_name = title_name;
  145. this.title_value = title_value;
  146. this.list_values = list_values;
  147. this.x = x;
  148. this.y = y;
  149. this.title_value_first = title_value_first;
  150. this.refresh();
  151. }
  152. hide_tip() {
  153. this.container.style.top = '0px';
  154. this.container.style.left = '0px';
  155. this.container.style.opacity = '0';
  156. }
  157. show_tip() {
  158. this.container.style.top = this.top + 'px';
  159. this.container.style.left = this.left + 'px';
  160. this.container.style.opacity = '1';
  161. }
  162. }
  163. /**
  164. * Returns the value of a number upto 2 decimal places.
  165. * @param {Number} d Any number
  166. */
  167. function floatTwo(d) {
  168. return parseFloat(d.toFixed(2));
  169. }
  170. /**
  171. * Returns whether or not two given arrays are equal.
  172. * @param {Array} arr1 First array
  173. * @param {Array} arr2 Second array
  174. */
  175. /**
  176. * Shuffles array in place. ES6 version
  177. * @param {Array} array An array containing the items.
  178. */
  179. /**
  180. * Fill an array with extra points
  181. * @param {Array} array Array
  182. * @param {Number} count number of filler elements
  183. * @param {Object} element element to fill with
  184. * @param {Boolean} start fill at start?
  185. */
  186. function fillArray(array, count, element, start=false) {
  187. if(!element) {
  188. element = start ? array[0] : array[array.length - 1];
  189. }
  190. let fillerArray = new Array(Math.abs(count)).fill(element);
  191. array = start ? fillerArray.concat(array) : array.concat(fillerArray);
  192. return array;
  193. }
  194. /**
  195. * Returns pixel width of string.
  196. * @param {String} string
  197. * @param {Number} charWidth Width of single char in pixels
  198. */
  199. const MIN_BAR_PERCENT_HEIGHT = 0.01;
  200. function getBarHeightAndYAttr(yTop, zeroLine, totalHeight) {
  201. let height, y;
  202. if (yTop <= zeroLine) {
  203. height = zeroLine - yTop;
  204. y = yTop;
  205. // In case of invisible bars
  206. if(height === 0) {
  207. height = totalHeight * MIN_BAR_PERCENT_HEIGHT;
  208. y -= height;
  209. }
  210. } else {
  211. height = yTop - zeroLine;
  212. y = zeroLine;
  213. // In case of invisible bars
  214. if(height === 0) {
  215. height = totalHeight * MIN_BAR_PERCENT_HEIGHT;
  216. }
  217. }
  218. return [height, y];
  219. }
  220. function equilizeNoOfElements(array1, array2,
  221. extra_count=array2.length - array1.length) {
  222. if(extra_count > 0) {
  223. array1 = fillArray(array1, extra_count);
  224. } else {
  225. array2 = fillArray(array2, extra_count);
  226. }
  227. return [array1, array2];
  228. }
  229. // let char_width = 8;
  230. // let allowed_space = avgUnitWidth * 1.5;
  231. // let allowed_letters = allowed_space / 8;
  232. // return values.map((value, i) => {
  233. // let space_taken = getStringWidth(value, char_width) + 2;
  234. // if(space_taken > allowed_space) {
  235. // if(is_series) {
  236. // // Skip some axis lines if X axis is a series
  237. // let skips = 1;
  238. // while((space_taken/skips)*2 > allowed_space) {
  239. // skips++;
  240. // }
  241. // if(i % skips !== 0) {
  242. // return;
  243. // }
  244. // } else {
  245. // value = value.slice(0, allowed_letters-3) + " ...";
  246. // }
  247. // }
  248. const AXIS_TICK_LENGTH = 6;
  249. const LABEL_MARGIN = 4;
  250. const FONT_SIZE = 10;
  251. function $$1(expr, con) {
  252. return typeof expr === "string"? (con || document).querySelector(expr) : expr || null;
  253. }
  254. function createSVG(tag, o) {
  255. var element = document.createElementNS("http://www.w3.org/2000/svg", tag);
  256. for (var i in o) {
  257. var val = o[i];
  258. if (i === "inside") {
  259. $$1(val).appendChild(element);
  260. }
  261. else if (i === "around") {
  262. var ref = $$1(val);
  263. ref.parentNode.insertBefore(element, ref);
  264. element.appendChild(ref);
  265. } else if (i === "styles") {
  266. if(typeof val === "object") {
  267. Object.keys(val).map(prop => {
  268. element.style[prop] = val[prop];
  269. });
  270. }
  271. } else {
  272. if(i === "className") { i = "class"; }
  273. if(i === "innerHTML") {
  274. element['textContent'] = val;
  275. } else {
  276. element.setAttribute(i, val);
  277. }
  278. }
  279. }
  280. return element;
  281. }
  282. function renderVerticalGradient(svgDefElem, gradientId) {
  283. return createSVG('linearGradient', {
  284. inside: svgDefElem,
  285. id: gradientId,
  286. x1: 0,
  287. x2: 0,
  288. y1: 0,
  289. y2: 1
  290. });
  291. }
  292. function setGradientStop(gradElem, offset, color, opacity) {
  293. return createSVG('stop', {
  294. 'inside': gradElem,
  295. 'style': `stop-color: ${color}`,
  296. 'offset': offset,
  297. 'stop-opacity': opacity
  298. });
  299. }
  300. function makeSVGContainer(parent, className, width, height) {
  301. return createSVG('svg', {
  302. className: className,
  303. inside: parent,
  304. width: width,
  305. height: height
  306. });
  307. }
  308. function makeSVGDefs(svgContainer) {
  309. return createSVG('defs', {
  310. inside: svgContainer,
  311. });
  312. }
  313. function makeSVGGroup(parent, className, transform='') {
  314. return createSVG('g', {
  315. className: className,
  316. inside: parent,
  317. transform: transform
  318. });
  319. }
  320. function makePath(pathStr, className='', stroke='none', fill='none') {
  321. return createSVG('path', {
  322. className: className,
  323. d: pathStr,
  324. styles: {
  325. stroke: stroke,
  326. fill: fill
  327. }
  328. });
  329. }
  330. function makeGradient(svgDefElem, color, lighter = false) {
  331. let gradientId ='path-fill-gradient' + '-' + color;
  332. let gradientDef = renderVerticalGradient(svgDefElem, gradientId);
  333. let opacities = [1, 0.6, 0.2];
  334. if(lighter) {
  335. opacities = [0.4, 0.2, 0];
  336. }
  337. setGradientStop(gradientDef, "0%", color, opacities[0]);
  338. setGradientStop(gradientDef, "50%", color, opacities[1]);
  339. setGradientStop(gradientDef, "100%", color, opacities[2]);
  340. return gradientId;
  341. }
  342. function makeHeatSquare(className, x, y, size, fill='none', data={}) {
  343. let args = {
  344. className: className,
  345. x: x,
  346. y: y,
  347. width: size,
  348. height: size,
  349. fill: fill
  350. };
  351. Object.keys(data).map(key => {
  352. args[key] = data[key];
  353. });
  354. return createSVG("rect", args);
  355. }
  356. function makeText(className, x, y, content) {
  357. return createSVG('text', {
  358. className: className,
  359. x: x,
  360. y: y,
  361. dy: (FONT_SIZE / 2) + 'px',
  362. 'font-size': FONT_SIZE + 'px',
  363. innerHTML: content
  364. });
  365. }
  366. function makeVertXLine(x, label, totalHeight, mode) {
  367. let height = mode === 'span' ? -1 * AXIS_TICK_LENGTH : totalHeight;
  368. let l = createSVG('line', {
  369. x1: 0,
  370. x2: 0,
  371. y1: totalHeight + AXIS_TICK_LENGTH,
  372. y2: height
  373. });
  374. let text = createSVG('text', {
  375. x: 0,
  376. y: totalHeight + AXIS_TICK_LENGTH + LABEL_MARGIN,
  377. dy: FONT_SIZE + 'px',
  378. 'font-size': FONT_SIZE + 'px',
  379. 'text-anchor': 'middle',
  380. innerHTML: label
  381. });
  382. let line = createSVG('g', {
  383. transform: `translate(${ x }, 0)`
  384. });
  385. line.appendChild(l);
  386. line.appendChild(text);
  387. return line;
  388. }
  389. function makeHoriYLine(y, label, totalWidth, mode) {
  390. let lineType = '';
  391. let width = mode === 'span' ? totalWidth + AXIS_TICK_LENGTH : AXIS_TICK_LENGTH;
  392. let l = createSVG('line', {
  393. className: lineType === "dashed" ? "dashed": "",
  394. x1: -1 * AXIS_TICK_LENGTH,
  395. x2: width,
  396. y1: 0,
  397. y2: 0
  398. });
  399. let text = createSVG('text', {
  400. x: -1 * (LABEL_MARGIN + AXIS_TICK_LENGTH),
  401. y: 0,
  402. dy: (FONT_SIZE / 2 - 2) + 'px',
  403. 'font-size': FONT_SIZE + 'px',
  404. 'text-anchor': 'end',
  405. innerHTML: label+""
  406. });
  407. let line = createSVG('g', {
  408. transform: `translate(0, ${y})`,
  409. 'stroke-opacity': 1
  410. });
  411. if(text === 0 || text === '0') {
  412. line.style.stroke = "rgba(27, 31, 35, 0.6)";
  413. }
  414. line.appendChild(l);
  415. line.appendChild(text);
  416. return line;
  417. }
  418. class AxisChartRenderer {
  419. constructor(state) {
  420. this.updateState(state);
  421. }
  422. updateState(state) {
  423. this.totalHeight = state.totalHeight;
  424. this.totalWidth = state.totalWidth;
  425. this.zeroLine = state.zeroLine;
  426. this.avgUnitWidth = state.avgUnitWidth;
  427. this.xAxisMode = state.xAxisMode;
  428. this.yAxisMode = state.yAxisMode;
  429. }
  430. bar(x, yTop, args, color, index, datasetIndex, noOfDatasets) {
  431. let totalWidth = this.avgUnitWidth - args.spaceWidth;
  432. let startX = x - totalWidth/2;
  433. let width = totalWidth / noOfDatasets;
  434. let currentX = startX + width * datasetIndex;
  435. let [height, y] = getBarHeightAndYAttr(yTop, this.zeroLine, this.totalHeight);
  436. return createSVG('rect', {
  437. className: `bar mini`,
  438. style: `fill: ${color}`,
  439. 'data-point-index': index,
  440. x: currentX,
  441. y: y,
  442. width: width,
  443. height: height
  444. });
  445. }
  446. dot(x, y, args, color, index) {
  447. return createSVG('circle', {
  448. style: `fill: ${color}`,
  449. 'data-point-index': index,
  450. cx: x,
  451. cy: y,
  452. r: args.radius
  453. });
  454. }
  455. xLine(x, label, mode=this.xAxisMode) {
  456. // Draw X axis line in span/tick mode with optional label
  457. return makeVertXLine(x, label, this.totalHeight, mode);
  458. }
  459. yLine(y, label, mode=this.yAxisMode) {
  460. return makeHoriYLine(y, label, this.totalWidth, mode);
  461. }
  462. xMarker() {}
  463. yMarker() {}
  464. xRegion() {}
  465. yRegion() {}
  466. }
  467. const PRESET_COLOR_MAP = {
  468. 'light-blue': '#7cd6fd',
  469. 'blue': '#5e64ff',
  470. 'violet': '#743ee2',
  471. 'red': '#ff5858',
  472. 'orange': '#ffa00a',
  473. 'yellow': '#feef72',
  474. 'green': '#28a745',
  475. 'light-green': '#98d85b',
  476. 'purple': '#b554ff',
  477. 'magenta': '#ffa3ef',
  478. 'black': '#36114C',
  479. 'grey': '#bdd3e6',
  480. 'light-grey': '#f0f4f7',
  481. 'dark-grey': '#b8c2cc'
  482. };
  483. const DEFAULT_COLORS = ['light-blue', 'blue', 'violet', 'red', 'orange',
  484. 'yellow', 'green', 'light-green', 'purple', 'magenta'];
  485. function limitColor(r){
  486. if (r > 255) return 255;
  487. else if (r < 0) return 0;
  488. return r;
  489. }
  490. function lightenDarkenColor(color, amt) {
  491. let col = getColor(color);
  492. let usePound = false;
  493. if (col[0] == "#") {
  494. col = col.slice(1);
  495. usePound = true;
  496. }
  497. let num = parseInt(col,16);
  498. let r = limitColor((num >> 16) + amt);
  499. let b = limitColor(((num >> 8) & 0x00FF) + amt);
  500. let g = limitColor((num & 0x0000FF) + amt);
  501. return (usePound?"#":"") + (g | (b << 8) | (r << 16)).toString(16);
  502. }
  503. function isValidColor(string) {
  504. // https://stackoverflow.com/a/8027444/6495043
  505. return /(^#[0-9A-F]{6}$)|(^#[0-9A-F]{3}$)/i.test(string);
  506. }
  507. const getColor = (color) => {
  508. return PRESET_COLOR_MAP[color] || color;
  509. };
  510. const ALL_CHART_TYPES = ['line', 'scatter', 'bar', 'percentage', 'heatmap', 'pie'];
  511. const COMPATIBLE_CHARTS = {
  512. bar: ['line', 'scatter', 'percentage', 'pie'],
  513. line: ['scatter', 'bar', 'percentage', 'pie'],
  514. pie: ['line', 'scatter', 'percentage', 'bar'],
  515. scatter: ['line', 'bar', 'percentage', 'pie'],
  516. percentage: ['bar', 'line', 'scatter', 'pie'],
  517. heatmap: []
  518. };
  519. // Needs structure as per only labels/datasets
  520. const COLOR_COMPATIBLE_CHARTS = {
  521. bar: ['line', 'scatter'],
  522. line: ['scatter', 'bar'],
  523. pie: ['percentage'],
  524. scatter: ['line', 'bar'],
  525. percentage: ['pie'],
  526. heatmap: []
  527. };
  528. function getDifferentChart(type, current_type, args) {
  529. if(type === current_type) return;
  530. if(!ALL_CHART_TYPES.includes(type)) {
  531. console.error(`'${type}' is not a valid chart type.`);
  532. }
  533. if(!COMPATIBLE_CHARTS[current_type].includes(type)) {
  534. console.error(`'${current_type}' chart cannot be converted to a '${type}' chart.`);
  535. }
  536. // whether the new chart can use the existing colors
  537. const useColor = COLOR_COMPATIBLE_CHARTS[current_type].includes(type);
  538. // Okay, this is anticlimactic
  539. // this function will need to actually be 'changeChartType(type)'
  540. // that will update only the required elements, but for now ...
  541. return new Chart({
  542. parent: args.parent,
  543. title: args.title,
  544. data: args.data,
  545. type: type,
  546. height: args.height,
  547. colors: useColor ? args.colors : undefined
  548. });
  549. }
  550. class BaseChart {
  551. constructor({
  552. height = 240,
  553. title = '',
  554. subtitle = '',
  555. colors = [],
  556. isNavigable = 0,
  557. type = '',
  558. parent,
  559. data
  560. }) {
  561. this.rawChartArgs = arguments[0];
  562. this.parent = typeof parent === 'string' ? document.querySelector(parent) : parent;
  563. this.title = title;
  564. this.subtitle = subtitle;
  565. this.isNavigable = isNavigable;
  566. if(this.isNavigable) {
  567. this.currentIndex = 0;
  568. }
  569. this.setupConfiguration();
  570. }
  571. setupConfiguration() {
  572. // Make a this.config, that has stuff like showTooltip,
  573. // showLegend, which then all functions will check
  574. this.setColors();
  575. this.setMargins();
  576. // constants
  577. this.config = {
  578. showTooltip: 1,
  579. showLegend: 1,
  580. isNavigable: 0,
  581. animate: 1
  582. };
  583. }
  584. setColors() {
  585. let args = this.rawChartArgs;
  586. // Needs structure as per only labels/datasets, from config
  587. const list = args.type === 'percentage' || args.type === 'pie'
  588. ? args.data.labels
  589. : args.data.datasets;
  590. if(!args.colors || (list && args.colors.length < list.length)) {
  591. this.colors = DEFAULT_COLORS;
  592. } else {
  593. this.colors = args.colors;
  594. }
  595. this.colors = this.colors.map(color => getColor(color));
  596. }
  597. setMargins() {
  598. let height = this.rawChartArgs.height;
  599. this.baseHeight = height;
  600. this.height = height - 40;
  601. this.translateX = 60;
  602. this.translateY = 10;
  603. }
  604. validate(){
  605. if(!this.parent) {
  606. console.error("No parent element to render on was provided.");
  607. return false;
  608. }
  609. if(!this.parseData()) {
  610. return false;
  611. }
  612. return true;
  613. }
  614. parseData() {
  615. let data = this.rawChartArgs.data;
  616. let valid = this.checkData(data);
  617. if(!valid) return false;
  618. if(!this.config.animate) {
  619. this.data = data;
  620. } else {
  621. [this.data, this.firstUpdateData] =
  622. this.getFirstUpdateData(data);
  623. }
  624. return true;
  625. }
  626. checkData() {}
  627. getFirstUpdateData(data) {}
  628. setup() {
  629. if(this.validate()) {
  630. this._setup();
  631. }
  632. }
  633. _setup() {
  634. this.bindWindowEvents();
  635. this.setupConstants();
  636. // this.setupComponents();
  637. this.makeContainer();
  638. this.makeTooltip(); // without binding
  639. this.draw(true);
  640. }
  641. bindWindowEvents() {
  642. window.addEventListener('resize orientationchange', () => this.draw());
  643. }
  644. setupConstants() {}
  645. setupComponents() {
  646. // Components config
  647. this.components = [];
  648. }
  649. makeContainer() {
  650. this.container = $.create('div', {
  651. className: 'chart-container',
  652. innerHTML: `<h6 class="title">${this.title}</h6>
  653. <h6 class="sub-title uppercase">${this.subtitle}</h6>
  654. <div class="frappe-chart graphics"></div>
  655. <div class="graph-stats-container"></div>`
  656. });
  657. // Chart needs a dedicated parent element
  658. this.parent.innerHTML = '';
  659. this.parent.appendChild(this.container);
  660. this.chartWrapper = this.container.querySelector('.frappe-chart');
  661. this.statsWrapper = this.container.querySelector('.graph-stats-container');
  662. }
  663. makeTooltip() {
  664. this.tip = new SvgTip({
  665. parent: this.chartWrapper,
  666. colors: this.colors
  667. });
  668. this.bindTooltip();
  669. }
  670. draw(init=false) {
  671. // difference from update(): draw the whole object due to groudbreaking event (init, resize, etc.)
  672. // (draw everything, layers, groups, units)
  673. this.calc();
  674. this.refreshRenderer(); // this chart's rendered with the config
  675. this.setupComponents();
  676. this.makeChartArea();
  677. this.makeLayers();
  678. this.renderComponents(); // with zero values
  679. this.renderLegend();
  680. this.setupNavigation(init);
  681. if(this.config.animate) this.update(this.firstUpdateData);
  682. }
  683. update() {
  684. // difference from draw(): yes you do rerender everything here as well,
  685. // but not things like the chart itself, mosty only at component level
  686. this.reCalc();
  687. this.reRender();
  688. }
  689. refreshRenderer() {}
  690. calcWidth() {
  691. let outerAnnotationsWidth = 0;
  692. // let charWidth = 8;
  693. // this.specificValues.map(val => {
  694. // let strWidth = getStringWidth((val.title + ""), charWidth);
  695. // if(strWidth > outerAnnotationsWidth) {
  696. // outerAnnotationsWidth = strWidth - 40;
  697. // }
  698. // });
  699. this.baseWidth = getElementContentWidth(this.parent) - outerAnnotationsWidth;
  700. this.width = this.baseWidth - this.translateX * 2;
  701. }
  702. calc() {
  703. this.calcWidth();
  704. this.reCalc();
  705. }
  706. makeChartArea() {
  707. this.svg = makeSVGContainer(
  708. this.chartWrapper,
  709. 'chart',
  710. this.baseWidth,
  711. this.baseHeight
  712. );
  713. this.svg_defs = makeSVGDefs(this.svg);
  714. this.drawArea = makeSVGGroup(
  715. this.svg,
  716. this.type + '-chart',
  717. `translate(${this.translateX}, ${this.translateY})`
  718. );
  719. }
  720. makeLayers() {
  721. this.components.forEach((component) => {
  722. component.layer = this.makeLayer(component.layerClass);
  723. });
  724. }
  725. calculateValues() {}
  726. renderComponents() {
  727. this.components.forEach(c => {
  728. c.store = c.make(...c.makeArgs);
  729. c.layer.textContent = '';
  730. c.store.forEach(element => {c.layer.appendChild(element);});
  731. });
  732. }
  733. reCalc() {
  734. // Will update values(state)
  735. // Will recalc specific parts depending on the update
  736. }
  737. reRender(animate=true) {
  738. if(!animate) {
  739. this.renderComponents();
  740. return;
  741. }
  742. this.animateComponents();
  743. setTimeout(() => {
  744. this.renderComponents();
  745. }, 400);
  746. // TODO: should be max anim duration required
  747. // (opt, should not redraw if still in animate?)
  748. }
  749. animateComponents() {
  750. this.intermedValues = this.calcIntermediateValues();
  751. this.components.forEach(c => {
  752. // c.store = c.animate(...c.animateArgs);
  753. // c.layer.textContent = '';
  754. // c.store.forEach(element => {c.layer.appendChild(element);});
  755. });
  756. }
  757. calcInitStage() {}
  758. renderLegend() {}
  759. setupNavigation(init=false) {
  760. if(this.isNavigable) return;
  761. this.makeOverlay();
  762. if(init) {
  763. this.bindOverlay();
  764. document.addEventListener('keydown', (e) => {
  765. if(isElementInViewport(this.chartWrapper)) {
  766. e = e || window.event;
  767. if (e.keyCode == '37') {
  768. this.onLeftArrow();
  769. } else if (e.keyCode == '39') {
  770. this.onRightArrow();
  771. } else if (e.keyCode == '38') {
  772. this.onUpArrow();
  773. } else if (e.keyCode == '40') {
  774. this.onDownArrow();
  775. } else if (e.keyCode == '13') {
  776. this.onEnterKey();
  777. }
  778. }
  779. });
  780. }
  781. }
  782. makeOverlay() {}
  783. bindOverlay() {}
  784. bind_units() {}
  785. onLeftArrow() {}
  786. onRightArrow() {}
  787. onUpArrow() {}
  788. onDownArrow() {}
  789. onEnterKey() {}
  790. getDataPoint() {}
  791. updateCurrentDataPoint() {}
  792. makeLayer(className, transform='') {
  793. return makeSVGGroup(this.drawArea, className, transform);
  794. }
  795. getDifferentChart(type) {
  796. return getDifferentChart(type, this.type, this.rawChartArgs);
  797. }
  798. }
  799. const UNIT_ANIM_DUR = 350;
  800. const PATH_ANIM_DUR = 650;
  801. const MARKER_LINE_ANIM_DUR = UNIT_ANIM_DUR;
  802. const REPLACE_ALL_NEW_DUR = 250;
  803. const STD_EASING = 'easein';
  804. var Animator = (function() {
  805. var Animator = function(totalHeight, totalWidth, zeroLine, avgUnitWidth) {
  806. // constants
  807. this.totalHeight = totalHeight;
  808. this.totalWidth = totalWidth;
  809. // changeables
  810. this.avgUnitWidth = avgUnitWidth;
  811. this.zeroLine = zeroLine;
  812. };
  813. Animator.prototype = {
  814. bar: function(barObj, x, yTop, index, noOfDatasets) {
  815. let start = x - this.avgUnitWidth/4;
  816. let width = (this.avgUnitWidth/2)/noOfDatasets;
  817. let [height, y] = getBarHeightAndYAttr(yTop, this.zeroLine, this.totalHeight);
  818. x = start + (width * index);
  819. return [barObj, {width: width, height: height, x: x, y: y}, UNIT_ANIM_DUR, STD_EASING];
  820. // bar.animate({height: args.newHeight, y: yTop}, UNIT_ANIM_DUR, mina.easein);
  821. },
  822. dot: function(dotObj, x, yTop) {
  823. return [dotObj, {cx: x, cy: yTop}, UNIT_ANIM_DUR, STD_EASING];
  824. // dot.animate({cy: yTop}, UNIT_ANIM_DUR, mina.easein);
  825. },
  826. path: function(d, pathStr) {
  827. let pathComponents = [];
  828. const animPath = [{unit: d.path, object: d, key: 'path'}, {d:"M"+pathStr}, PATH_ANIM_DUR, STD_EASING];
  829. pathComponents.push(animPath);
  830. if(d.regionPath) {
  831. let regStartPt = `0,${this.zeroLine}L`;
  832. let regEndPt = `L${this.totalWidth}, ${this.zeroLine}`;
  833. const animRegion = [
  834. {unit: d.regionPath, object: d, key: 'regionPath'},
  835. {d:"M" + regStartPt + pathStr + regEndPt},
  836. PATH_ANIM_DUR,
  837. STD_EASING
  838. ];
  839. pathComponents.push(animRegion);
  840. }
  841. return pathComponents;
  842. },
  843. translate: function(obj, oldCoord, newCoord, duration) {
  844. return [
  845. {unit: obj, array: [0], index: 0},
  846. {transform: newCoord.join(', ')},
  847. duration,
  848. STD_EASING,
  849. "translate",
  850. {transform: oldCoord.join(', ')}
  851. ];
  852. },
  853. verticalLine: function(xLine, newX, oldX) {
  854. return this.translate(xLine, [oldX, 0], [newX, 0], MARKER_LINE_ANIM_DUR);
  855. },
  856. horizontalLine: function(yLine, newY, oldY) {
  857. return this.translate(yLine, [0, oldY], [0, newY], MARKER_LINE_ANIM_DUR);
  858. }
  859. };
  860. return Animator;
  861. })();
  862. // export function animateXLines(animator, lines, oldX, newX) {
  863. // // this.xAxisLines.map((xLine, i) => {
  864. // return lines.map((xLine, i) => {
  865. // return animator.verticalLine(xLine, newX[i], oldX[i]);
  866. // });
  867. // }
  868. // export function animateYLines(animator, lines, oldY, newY) {
  869. // // this.yAxisLines.map((yLine, i) => {
  870. // lines.map((yLine, i) => {
  871. // return animator.horizontalLine(yLine, newY[i], oldY[i]);
  872. // });
  873. // }
  874. // Leveraging SMIL Animations
  875. const EASING = {
  876. ease: "0.25 0.1 0.25 1",
  877. linear: "0 0 1 1",
  878. // easein: "0.42 0 1 1",
  879. easein: "0.1 0.8 0.2 1",
  880. easeout: "0 0 0.58 1",
  881. easeinout: "0.42 0 0.58 1"
  882. };
  883. function animateSVGElement(element, props, dur, easingType="linear", type=undefined, oldValues={}) {
  884. let animElement = element.cloneNode(true);
  885. let newElement = element.cloneNode(true);
  886. for(var attributeName in props) {
  887. let animateElement;
  888. if(attributeName === 'transform') {
  889. animateElement = document.createElementNS("http://www.w3.org/2000/svg", "animateTransform");
  890. } else {
  891. animateElement = document.createElementNS("http://www.w3.org/2000/svg", "animate");
  892. }
  893. let currentValue = oldValues[attributeName] || element.getAttribute(attributeName);
  894. let value = props[attributeName];
  895. let animAttr = {
  896. attributeName: attributeName,
  897. from: currentValue,
  898. to: value,
  899. begin: "0s",
  900. dur: dur/1000 + "s",
  901. values: currentValue + ";" + value,
  902. keySplines: EASING[easingType],
  903. keyTimes: "0;1",
  904. calcMode: "spline",
  905. fill: 'freeze'
  906. };
  907. if(type) {
  908. animAttr["type"] = type;
  909. }
  910. for (var i in animAttr) {
  911. animateElement.setAttribute(i, animAttr[i]);
  912. }
  913. animElement.appendChild(animateElement);
  914. if(type) {
  915. newElement.setAttribute(attributeName, `translate(${value})`);
  916. } else {
  917. newElement.setAttribute(attributeName, value);
  918. }
  919. }
  920. return [animElement, newElement];
  921. }
  922. function transform(element, style) { // eslint-disable-line no-unused-vars
  923. element.style.transform = style;
  924. element.style.webkitTransform = style;
  925. element.style.msTransform = style;
  926. element.style.mozTransform = style;
  927. element.style.oTransform = style;
  928. }
  929. function animateSVG(svgContainer, elements) {
  930. let newElements = [];
  931. let animElements = [];
  932. elements.map(element => {
  933. let obj = element[0];
  934. let parent = obj.unit.parentNode;
  935. let animElement, newElement;
  936. element[0] = obj.unit;
  937. [animElement, newElement] = animateSVGElement(...element);
  938. newElements.push(newElement);
  939. animElements.push([animElement, parent]);
  940. parent.replaceChild(animElement, obj.unit);
  941. if(obj.array) {
  942. obj.array[obj.index] = newElement;
  943. } else {
  944. obj.object[obj.key] = newElement;
  945. }
  946. });
  947. let animSvg = svgContainer.cloneNode(true);
  948. animElements.map((animElement, i) => {
  949. animElement[1].replaceChild(newElements[i], animElement[0]);
  950. elements[i][0] = newElements[i];
  951. });
  952. return animSvg;
  953. }
  954. function runSMILAnimation(parent, svgElement, elementsToAnimate) {
  955. if(elementsToAnimate.length === 0) return;
  956. let animSvgElement = animateSVG(svgElement, elementsToAnimate);
  957. if(svgElement.parentNode == parent) {
  958. parent.removeChild(svgElement);
  959. parent.appendChild(animSvgElement);
  960. }
  961. // Replace the new svgElement (data has already been replaced)
  962. setTimeout(() => {
  963. if(animSvgElement.parentNode == parent) {
  964. parent.removeChild(animSvgElement);
  965. parent.appendChild(svgElement);
  966. }
  967. }, REPLACE_ALL_NEW_DUR);
  968. }
  969. function normalize(x) {
  970. // Calculates mantissa and exponent of a number
  971. // Returns normalized number and exponent
  972. // https://stackoverflow.com/q/9383593/6495043
  973. if(x===0) {
  974. return [0, 0];
  975. }
  976. if(isNaN(x)) {
  977. return {mantissa: -6755399441055744, exponent: 972};
  978. }
  979. var sig = x > 0 ? 1 : -1;
  980. if(!isFinite(x)) {
  981. return {mantissa: sig * 4503599627370496, exponent: 972};
  982. }
  983. x = Math.abs(x);
  984. var exp = Math.floor(Math.log10(x));
  985. var man = x/Math.pow(10, exp);
  986. return [sig * man, exp];
  987. }
  988. function getRangeIntervals(max, min=0) {
  989. let upperBound = Math.ceil(max);
  990. let lowerBound = Math.floor(min);
  991. let range = upperBound - lowerBound;
  992. let noOfParts = range;
  993. let partSize = 1;
  994. // To avoid too many partitions
  995. if(range > 5) {
  996. if(range % 2 !== 0) {
  997. upperBound++;
  998. // Recalc range
  999. range = upperBound - lowerBound;
  1000. }
  1001. noOfParts = range/2;
  1002. partSize = 2;
  1003. }
  1004. // Special case: 1 and 2
  1005. if(range <= 2) {
  1006. noOfParts = 4;
  1007. partSize = range/noOfParts;
  1008. }
  1009. // Special case: 0
  1010. if(range === 0) {
  1011. noOfParts = 5;
  1012. partSize = 1;
  1013. }
  1014. let intervals = [];
  1015. for(var i = 0; i <= noOfParts; i++){
  1016. intervals.push(lowerBound + partSize * i);
  1017. }
  1018. return intervals;
  1019. }
  1020. function getIntervals(maxValue, minValue=0) {
  1021. let [normalMaxValue, exponent] = normalize(maxValue);
  1022. let normalMinValue = minValue ? minValue/Math.pow(10, exponent): 0;
  1023. // Allow only 7 significant digits
  1024. normalMaxValue = normalMaxValue.toFixed(6);
  1025. let intervals = getRangeIntervals(normalMaxValue, normalMinValue);
  1026. intervals = intervals.map(value => value * Math.pow(10, exponent));
  1027. return intervals;
  1028. }
  1029. function calcIntervals(values, withMinimum=false) {
  1030. //*** Where the magic happens ***
  1031. // Calculates best-fit y intervals from given values
  1032. // and returns the interval array
  1033. let maxValue = Math.max(...values);
  1034. let minValue = Math.min(...values);
  1035. // Exponent to be used for pretty print
  1036. let exponent = 0, intervals = []; // eslint-disable-line no-unused-vars
  1037. function getPositiveFirstIntervals(maxValue, absMinValue) {
  1038. let intervals = getIntervals(maxValue);
  1039. let intervalSize = intervals[1] - intervals[0];
  1040. // Then unshift the negative values
  1041. let value = 0;
  1042. for(var i = 1; value < absMinValue; i++) {
  1043. value += intervalSize;
  1044. intervals.unshift((-1) * value);
  1045. }
  1046. return intervals;
  1047. }
  1048. // CASE I: Both non-negative
  1049. if(maxValue >= 0 && minValue >= 0) {
  1050. exponent = normalize(maxValue)[1];
  1051. if(!withMinimum) {
  1052. intervals = getIntervals(maxValue);
  1053. } else {
  1054. intervals = getIntervals(maxValue, minValue);
  1055. }
  1056. }
  1057. // CASE II: Only minValue negative
  1058. else if(maxValue > 0 && minValue < 0) {
  1059. // `withMinimum` irrelevant in this case,
  1060. // We'll be handling both sides of zero separately
  1061. // (both starting from zero)
  1062. // Because ceil() and floor() behave differently
  1063. // in those two regions
  1064. let absMinValue = Math.abs(minValue);
  1065. if(maxValue >= absMinValue) {
  1066. exponent = normalize(maxValue)[1];
  1067. intervals = getPositiveFirstIntervals(maxValue, absMinValue);
  1068. } else {
  1069. // Mirror: maxValue => absMinValue, then change sign
  1070. exponent = normalize(absMinValue)[1];
  1071. let posIntervals = getPositiveFirstIntervals(absMinValue, maxValue);
  1072. intervals = posIntervals.map(d => d * (-1));
  1073. }
  1074. }
  1075. // CASE III: Both non-positive
  1076. else if(maxValue <= 0 && minValue <= 0) {
  1077. // Mirrored Case I:
  1078. // Work with positives, then reverse the sign and array
  1079. let pseudoMaxValue = Math.abs(minValue);
  1080. let pseudoMinValue = Math.abs(maxValue);
  1081. exponent = normalize(pseudoMaxValue)[1];
  1082. if(!withMinimum) {
  1083. intervals = getIntervals(pseudoMaxValue);
  1084. } else {
  1085. intervals = getIntervals(pseudoMaxValue, pseudoMinValue);
  1086. }
  1087. intervals = intervals.reverse().map(d => d * (-1));
  1088. }
  1089. return intervals;
  1090. }
  1091. function calcDistribution(values, distributionSize) {
  1092. // Assume non-negative values,
  1093. // implying distribution minimum at zero
  1094. let dataMaxValue = Math.max(...values);
  1095. let distributionStep = 1 / (distributionSize - 1);
  1096. let distribution = [];
  1097. for(var i = 0; i < distributionSize; i++) {
  1098. let checkpoint = dataMaxValue * (distributionStep * i);
  1099. distribution.push(checkpoint);
  1100. }
  1101. return distribution;
  1102. }
  1103. function getMaxCheckpoint(value, distribution) {
  1104. return distribution.filter(d => d < value).length;
  1105. }
  1106. class AxisChart extends BaseChart {
  1107. constructor(args) {
  1108. super(args);
  1109. this.is_series = args.is_series;
  1110. this.format_tooltip_y = args.format_tooltip_y;
  1111. this.format_tooltip_x = args.format_tooltip_x;
  1112. this.zeroLine = this.height;
  1113. }
  1114. parseData() {
  1115. let args = this.rawChartArgs;
  1116. this.xAxisLabels = args.data.labels || [];
  1117. this.y = args.data.datasets || [];
  1118. this.y.forEach(function(d, i) {
  1119. d.index = i;
  1120. }, this);
  1121. return true;
  1122. }
  1123. reCalc() {
  1124. // examples:
  1125. // [A] Dimension change:
  1126. // [B] Data change:
  1127. // 1. X values update
  1128. // 2. Y values update
  1129. // Aka all the values(state), these all will be documented in an old values object
  1130. // Backup first!
  1131. this.oldValues = ["everything"];
  1132. // extracted, raw args will remain in their own object
  1133. this.datasetsLabels = [];
  1134. this.datasetsValues = [[[12, 34, 68], [10, 5, 46]], [[20, 20, 20]]];
  1135. // CALCULATION: we'll need the first batch of calcs
  1136. // List of what will happen:
  1137. // this.xOffset = 0;
  1138. // this.unitWidth = 0;
  1139. // this.scaleMultipliers = [];
  1140. // this.datasetsPoints =
  1141. // Now, the function calls
  1142. // var merged = [].concat(...arrays)
  1143. // INIT
  1144. // axes
  1145. this.yAxisPositions = [this.height, this.height/2, 0];
  1146. this.yAxisLabels = ['0', '5', '10'];
  1147. this.xPositions = [0, this.width/2, this.width];
  1148. this.xAxisLabels = ['0', '5', '10'];
  1149. }
  1150. calcInitStage() {
  1151. // will borrow from the full recalc function
  1152. }
  1153. calcIntermediateValues() {
  1154. //
  1155. }
  1156. // this should be inherent in BaseChart
  1157. refreshRenderer() {
  1158. // These args are basically the current state of the chart,
  1159. // with constant and alive params mixed
  1160. this.renderer = new AxisChartRenderer({
  1161. totalHeight: this.height,
  1162. totalWidth: this.width,
  1163. zeroLine: this.zeroLine,
  1164. avgUnitWidth: this.avgUnitWidth,
  1165. xAxisMode: this.xAxisMode,
  1166. yAxisMode: this.yAxisMode
  1167. });
  1168. }
  1169. setupComponents() {
  1170. // Must have access to all current data things
  1171. let self = this;
  1172. this.yAxis = {
  1173. layerClass: 'y axis',
  1174. layer: undefined,
  1175. make: self.makeYLines.bind(self),
  1176. makeArgs: [self.yAxisPositions, self.yAxisLabels],
  1177. store: [],
  1178. // animate? or update? will come to while implementing
  1179. animate: self.animateYLines,
  1180. // indexed: 1 // ?? As per datasets?
  1181. };
  1182. this.xAxis = {
  1183. layerClass: 'x axis',
  1184. layer: undefined,
  1185. make: self.makeXLines.bind(self),
  1186. // TODO: will implement series skip with avgUnitWidth and isSeries later
  1187. makeArgs: [self.xPositions, self.xAxisLabels],
  1188. store: [],
  1189. animate: self.animateXLines
  1190. };
  1191. // Indexed according to dataset
  1192. // this.dataUnits = {
  1193. // layerClass: 'y marker axis',
  1194. // layer: undefined,
  1195. // make: makeXLines,
  1196. // makeArgs: [this.xPositions, this.xAxisLabels],
  1197. // store: [],
  1198. // animate: animateXLines,
  1199. // indexed: 1
  1200. // };
  1201. this.yMarkerLines = {
  1202. // layerClass: 'y marker axis',
  1203. // layer: undefined,
  1204. // make: makeYMarkerLines,
  1205. // makeArgs: [this.yMarkerPositions, this.yMarker],
  1206. // store: [],
  1207. // animate: animateYMarkerLines
  1208. };
  1209. this.xMarkerLines = {
  1210. // layerClass: 'x marker axis',
  1211. // layer: undefined,
  1212. // make: makeXMarkerLines,
  1213. // makeArgs: [this.xMarkerPositions, this.xMarker],
  1214. // store: [],
  1215. // animate: animateXMarkerLines
  1216. };
  1217. // Marker Regions
  1218. this.components = [
  1219. this.yAxis,
  1220. this.xAxis,
  1221. // this.yMarkerLines,
  1222. // this.xMarkerLines,
  1223. // this.dataUnits,
  1224. ];
  1225. }
  1226. setup_values() {
  1227. this.data.datasets.map(d => {
  1228. d.values = d.values.map(val => (!isNaN(val) ? val : 0));
  1229. });
  1230. this.setup_x();
  1231. this.setup_y();
  1232. }
  1233. setup_x() {
  1234. this.set_avgUnitWidth_and_x_offset();
  1235. if(this.xPositions) {
  1236. this.x_old_axis_positions = this.xPositions.slice();
  1237. }
  1238. this.xPositions = this.xAxisLabels.map((d, i) =>
  1239. floatTwo(this.x_offset + i * this.avgUnitWidth));
  1240. if(!this.x_old_axis_positions) {
  1241. this.x_old_axis_positions = this.xPositions.slice();
  1242. }
  1243. }
  1244. setup_y() {
  1245. if(this.yAxisLabels) {
  1246. this.y_old_axis_values = this.yAxisLabels.slice();
  1247. }
  1248. let values = this.get_all_y_values();
  1249. if(this.y_sums && this.y_sums.length > 0) {
  1250. values = values.concat(this.y_sums);
  1251. }
  1252. this.yAxisLabels = calcIntervals(values, this.type === 'line');
  1253. if(!this.y_old_axis_values) {
  1254. this.y_old_axis_values = this.yAxisLabels.slice();
  1255. }
  1256. const y_pts = this.yAxisLabels;
  1257. const value_range = y_pts[y_pts.length-1] - y_pts[0];
  1258. if(this.multiplier) this.old_multiplier = this.multiplier;
  1259. this.multiplier = this.height / value_range;
  1260. if(!this.old_multiplier) this.old_multiplier = this.multiplier;
  1261. const interval = y_pts[1] - y_pts[0];
  1262. const interval_height = interval * this.multiplier;
  1263. let zero_index;
  1264. if(y_pts.indexOf(0) >= 0) {
  1265. // the range has a given zero
  1266. // zero-line on the chart
  1267. zero_index = y_pts.indexOf(0);
  1268. } else if(y_pts[0] > 0) {
  1269. // Minimum value is positive
  1270. // zero-line is off the chart: below
  1271. let min = y_pts[0];
  1272. zero_index = (-1) * min / interval;
  1273. } else {
  1274. // Maximum value is negative
  1275. // zero-line is off the chart: above
  1276. let max = y_pts[y_pts.length - 1];
  1277. zero_index = (-1) * max / interval + (y_pts.length - 1);
  1278. }
  1279. if(this.zeroLine) this.old_zeroLine = this.zeroLine;
  1280. this.zeroLine = this.height - (zero_index * interval_height);
  1281. if(!this.old_zeroLine) this.old_zeroLine = this.zeroLine;
  1282. // Make positions arrays for y elements
  1283. if(this.yAxisPositions) this.oldYAxisPositions = this.yAxisPositions;
  1284. this.yAxisPositions = this.yAxisLabels.map(d => this.zeroLine - d * this.multiplier);
  1285. if(!this.oldYAxisPositions) this.oldYAxisPositions = this.yAxisPositions;
  1286. // if(this.yAnnotationPositions) this.oldYAnnotationPositions = this.yAnnotationPositions;
  1287. // this.yAnnotationPositions = this.specific_values.map(d => this.zeroLine - d.value * this.multiplier);
  1288. // if(!this.oldYAnnotationPositions) this.oldYAnnotationPositions = this.yAnnotationPositions;
  1289. }
  1290. makeXLines(positions, values) {
  1291. // TODO: draw as per condition (with/without label etc.)
  1292. return positions.map((position, i) => this.renderer.xLine(position, values[i]));
  1293. }
  1294. makeYLines(positions, values) {
  1295. return positions.map((position, i) => this.renderer.yLine(position, values[i]));
  1296. }
  1297. draw_graph(init=false) {
  1298. // TODO: NO INIT!
  1299. if(this.raw_chart_args.hasOwnProperty("init") && !this.raw_chart_args.init) {
  1300. this.y.map((d, i) => {
  1301. d.svg_units = [];
  1302. this.make_path && this.make_path(d, this.xPositions, d.yUnitPositions, this.colors[i]);
  1303. this.makeUnits(d);
  1304. this.calcYDependencies();
  1305. });
  1306. return;
  1307. }
  1308. if(init) {
  1309. this.draw_new_graph_and_animate();
  1310. return;
  1311. }
  1312. this.y.map((d, i) => {
  1313. d.svg_units = [];
  1314. this.make_path && this.make_path(d, this.xPositions, d.yUnitPositions, this.colors[i]);
  1315. this.makeUnits(d);
  1316. });
  1317. }
  1318. draw_new_graph_and_animate() {
  1319. let data = [];
  1320. this.y.map((d, i) => {
  1321. // Anim: Don't draw initial values, store them and update later
  1322. d.yUnitPositions = new Array(d.values.length).fill(this.zeroLine); // no value
  1323. data.push({values: d.values});
  1324. d.svg_units = [];
  1325. this.make_path && this.make_path(d, this.xPositions, d.yUnitPositions, this.colors[i]);
  1326. this.makeUnits(d);
  1327. });
  1328. setTimeout(() => {
  1329. this.updateData(data);
  1330. }, 350);
  1331. }
  1332. setupNavigation(init) {
  1333. if(init) {
  1334. // Hack: defer nav till initial updateData
  1335. setTimeout(() => {
  1336. super.setupNavigation(init);
  1337. }, 500);
  1338. } else {
  1339. super.setupNavigation(init);
  1340. }
  1341. }
  1342. makeUnits(d) {
  1343. this.makeDatasetUnits(
  1344. this.xPositions,
  1345. d.yUnitPositions,
  1346. this.colors[d.index],
  1347. d.index,
  1348. this.y.length
  1349. );
  1350. }
  1351. makeDatasetUnits(x_values, y_values, color, dataset_index,
  1352. no_of_datasets, units_group, units_array, unit) {
  1353. if(!units_group) units_group = this.svg_units_groups[dataset_index];
  1354. if(!units_array) units_array = this.y[dataset_index].svg_units;
  1355. if(!unit) unit = this.unit_args;
  1356. units_group.textContent = '';
  1357. units_array.length = 0;
  1358. let unit_AxisChartRenderer = new AxisChartRenderer(this.height, this.zeroLine, this.avgUnitWidth);
  1359. y_values.map((y, i) => {
  1360. let data_unit = unit_AxisChartRenderer[unit.type](
  1361. x_values[i],
  1362. y,
  1363. unit.args,
  1364. color,
  1365. i,
  1366. dataset_index,
  1367. no_of_datasets
  1368. );
  1369. units_group.appendChild(data_unit);
  1370. units_array.push(data_unit);
  1371. });
  1372. if(this.isNavigable) {
  1373. this.bind_units(units_array);
  1374. }
  1375. }
  1376. bindTooltip() {
  1377. // TODO: could be in tooltip itself, as it is a given functionality for its parent
  1378. this.chartWrapper.addEventListener('mousemove', (e) => {
  1379. let offset = getOffset(this.chartWrapper);
  1380. let relX = e.pageX - offset.left - this.translateX;
  1381. let relY = e.pageY - offset.top - this.translateY;
  1382. if(relY < this.height + this.translateY * 2) {
  1383. this.mapTooltipXPosition(relX);
  1384. } else {
  1385. this.tip.hide_tip();
  1386. }
  1387. });
  1388. }
  1389. mapTooltipXPosition(relX) {
  1390. if(!this.y_min_tops) return;
  1391. let titles = this.xAxisLabels;
  1392. if(this.format_tooltip_x && this.format_tooltip_x(this.xAxisLabels[0])) {
  1393. titles = this.xAxisLabels.map(d=>this.format_tooltip_x(d));
  1394. }
  1395. let y_format = this.format_tooltip_y && this.format_tooltip_y(this.y[0].values[0]);
  1396. for(var i=this.xPositions.length - 1; i >= 0 ; i--) {
  1397. let x_val = this.xPositions[i];
  1398. // let delta = i === 0 ? this.avgUnitWidth : x_val - this.xPositions[i-1];
  1399. if(relX > x_val - this.avgUnitWidth/2) {
  1400. let x = x_val + this.translateX;
  1401. let y = this.y_min_tops[i] + this.translateY;
  1402. let title = titles[i];
  1403. let values = this.y.map((set, j) => {
  1404. return {
  1405. title: set.title,
  1406. value: y_format ? this.format_tooltip_y(set.values[i]) : set.values[i],
  1407. color: this.colors[j],
  1408. };
  1409. });
  1410. this.tip.set_values(x, y, title, '', values);
  1411. this.tip.show_tip();
  1412. break;
  1413. }
  1414. }
  1415. }
  1416. // API
  1417. updateData(newY, newX) {
  1418. if(!newX) {
  1419. newX = this.xAxisLabels;
  1420. }
  1421. this.updating = true;
  1422. this.old_x_values = this.xAxisLabels.slice();
  1423. this.old_y_axis_tops = this.y.map(d => d.yUnitPositions.slice());
  1424. this.old_y_values = this.y.map(d => d.values);
  1425. // Just update values prop, setup_x/y() will do the rest
  1426. if(newY) this.y.map(d => {d.values = newY[d.index].values;});
  1427. if(newX) this.xAxisLabels = newX;
  1428. this.setup_x();
  1429. this.setup_y();
  1430. // Change in data, so calculate dependencies
  1431. this.calcYDependencies();
  1432. // Got the values? Now begin drawing
  1433. this.animator = new Animator(this.height, this.width, this.zeroLine, this.avgUnitWidth);
  1434. this.animate_graphs();
  1435. this.updating = false;
  1436. }
  1437. animate_graphs() {
  1438. this.elements_to_animate = [];
  1439. // Pre-prep, equilize no of positions between old and new
  1440. let [old_x, newX] = equilizeNoOfElements(
  1441. this.x_old_axis_positions.slice(),
  1442. this.xPositions.slice()
  1443. );
  1444. let [oldYAxis, newYAxis] = equilizeNoOfElements(
  1445. this.oldYAxisPositions.slice(),
  1446. this.yAxisPositions.slice()
  1447. );
  1448. let newXValues = this.xAxisLabels.slice();
  1449. let newYValues = this.yAxisLabels.slice();
  1450. let extra_points = this.xPositions.slice().length - this.x_old_axis_positions.slice().length;
  1451. if(extra_points > 0) {
  1452. this.makeXLines(old_x, newXValues);
  1453. }
  1454. // No Y extra check?
  1455. this.makeYLines(oldYAxis, newYValues);
  1456. // Animation
  1457. if(extra_points !== 0) {
  1458. this.animateXLines(old_x, newX);
  1459. }
  1460. this.animateYLines(oldYAxis, newYAxis);
  1461. this.y.map(d => {
  1462. let [old_y, newY] = equilizeNoOfElements(
  1463. this.old_y_axis_tops[d.index].slice(),
  1464. d.yUnitPositions.slice()
  1465. );
  1466. if(extra_points > 0) {
  1467. this.make_path && this.make_path(d, old_x, old_y, this.colors[d.index]);
  1468. this.makeDatasetUnits(old_x, old_y, this.colors[d.index], d.index, this.y.length);
  1469. }
  1470. // Animation
  1471. d.path && this.animate_path(d, newX, newY);
  1472. this.animate_units(d, newX, newY);
  1473. });
  1474. runSMILAnimation(this.chartWrapper, this.svg, this.elements_to_animate);
  1475. setTimeout(() => {
  1476. this.y.map(d => {
  1477. this.make_path && this.make_path(d, this.xPositions, d.yUnitPositions, this.colors[d.index]);
  1478. this.makeUnits(d);
  1479. this.makeYLines(this.yAxisPositions, this.yAxisLabels);
  1480. this.makeXLines(this.xPositions, this.xAxisLabels);
  1481. // this.make_y_specifics(this.yAnnotationPositions, this.specific_values);
  1482. });
  1483. }, 400);
  1484. }
  1485. animate_path(d, newX, newY) {
  1486. const newPointsList = newY.map((y, i) => (newX[i] + ',' + y));
  1487. this.elements_to_animate = this.elements_to_animate
  1488. .concat(this.animator.path(d, newPointsList.join("L")));
  1489. }
  1490. animate_units(d, newX, newY) {
  1491. let type = this.unit_args.type;
  1492. d.svg_units.map((unit, i) => {
  1493. if(newX[i] === undefined || newY[i] === undefined) return;
  1494. this.elements_to_animate.push(this.animator[type](
  1495. {unit:unit, array:d.svg_units, index: i}, // unit, with info to replace where it came from in the data
  1496. newX[i],
  1497. newY[i],
  1498. d.index,
  1499. this.y.length
  1500. ));
  1501. });
  1502. }
  1503. animateXLines(oldX, newX) {
  1504. this.xAxisLines.map((xLine, i) => {
  1505. this.elements_to_animate.push(this.animator.verticalLine(
  1506. xLine, newX[i], oldX[i]
  1507. ));
  1508. });
  1509. }
  1510. animateYLines(oldY, newY) {
  1511. this.yAxisLines.map((yLine, i) => {
  1512. this.elements_to_animate.push(this.animator.horizontalLine(
  1513. yLine, newY[i], oldY[i]
  1514. ));
  1515. });
  1516. }
  1517. animateYAnnotations() {
  1518. //
  1519. }
  1520. add_data_point(y_point, x_point, index=this.xAxisLabels.length) {
  1521. let newY = this.y.map(data_set => { return {values:data_set.values}; });
  1522. newY.map((d, i) => { d.values.splice(index, 0, y_point[i]); });
  1523. let newX = this.xAxisLabels.slice();
  1524. newX.splice(index, 0, x_point);
  1525. this.updateData(newY, newX);
  1526. }
  1527. remove_data_point(index = this.xAxisLabels.length-1) {
  1528. if(this.xAxisLabels.length < 3) return;
  1529. let newY = this.y.map(data_set => { return {values:data_set.values}; });
  1530. newY.map((d) => { d.values.splice(index, 1); });
  1531. let newX = this.xAxisLabels.slice();
  1532. newX.splice(index, 1);
  1533. this.updateData(newY, newX);
  1534. }
  1535. getDataPoint(index=this.currentIndex) {
  1536. // check for length
  1537. let data_point = {
  1538. index: index
  1539. };
  1540. let y = this.y[0];
  1541. ['svg_units', 'yUnitPositions', 'values'].map(key => {
  1542. let data_key = key.slice(0, key.length-1);
  1543. data_point[data_key] = y[key][index];
  1544. });
  1545. data_point.label = this.xAxisLabels[index];
  1546. return data_point;
  1547. }
  1548. updateCurrentDataPoint(index) {
  1549. index = parseInt(index);
  1550. if(index < 0) index = 0;
  1551. if(index >= this.xAxisLabels.length) index = this.xAxisLabels.length - 1;
  1552. if(index === this.currentIndex) return;
  1553. this.currentIndex = index;
  1554. fire(this.parent, "data-select", this.getDataPoint());
  1555. }
  1556. set_avgUnitWidth_and_x_offset() {
  1557. // Set the ... you get it
  1558. this.avgUnitWidth = this.width/(this.xAxisLabels.length - 1);
  1559. this.x_offset = 0;
  1560. }
  1561. get_all_y_values() {
  1562. let all_values = [];
  1563. // Add in all the y values in the datasets
  1564. this.y.map(d => {
  1565. all_values = all_values.concat(d.values);
  1566. });
  1567. // Add in all the specific values
  1568. return all_values.concat(this.specific_values.map(d => d.value));
  1569. }
  1570. calcYDependencies() {
  1571. this.y_min_tops = new Array(this.xAxisLabels.length).fill(9999);
  1572. this.y.map(d => {
  1573. d.yUnitPositions = d.values.map( val => floatTwo(this.zeroLine - val * this.multiplier));
  1574. d.yUnitPositions.map( (yUnitPosition, i) => {
  1575. if(yUnitPosition < this.y_min_tops[i]) {
  1576. this.y_min_tops[i] = yUnitPosition;
  1577. }
  1578. });
  1579. });
  1580. // this.chartWrapper.removeChild(this.tip.container);
  1581. // this.make_tooltip();
  1582. }
  1583. }
  1584. class BarChart extends AxisChart {
  1585. constructor(args) {
  1586. super(args);
  1587. this.type = 'bar';
  1588. this.xAxisMode = args.xAxisMode || 'tick';
  1589. this.yAxisMode = args.yAxisMode || 'span';
  1590. this.setup();
  1591. }
  1592. setup_values() {
  1593. super.setup_values();
  1594. this.x_offset = this.avgUnitWidth;
  1595. this.unit_args = {
  1596. type: 'bar',
  1597. args: {
  1598. spaceWidth: this.avgUnitWidth/2,
  1599. }
  1600. };
  1601. }
  1602. // makeOverlay() {
  1603. // // Just make one out of the first element
  1604. // let index = this.xAxisLabels.length - 1;
  1605. // let unit = this.y[0].svg_units[index];
  1606. // this.updateCurrentDataPoint(index);
  1607. // if(this.overlay) {
  1608. // this.overlay.parentNode.removeChild(this.overlay);
  1609. // }
  1610. // this.overlay = unit.cloneNode();
  1611. // this.overlay.style.fill = '#000000';
  1612. // this.overlay.style.opacity = '0.4';
  1613. // this.drawArea.appendChild(this.overlay);
  1614. // }
  1615. // bindOverlay() {
  1616. // // on event, update overlay
  1617. // this.parent.addEventListener('data-select', (e) => {
  1618. // this.update_overlay(e.svg_unit);
  1619. // });
  1620. // }
  1621. bind_units(units_array) {
  1622. units_array.map(unit => {
  1623. unit.addEventListener('click', () => {
  1624. let index = unit.getAttribute('data-point-index');
  1625. this.updateCurrentDataPoint(index);
  1626. });
  1627. });
  1628. }
  1629. update_overlay(unit) {
  1630. let attributes = [];
  1631. Object.keys(unit.attributes).map(index => {
  1632. attributes.push(unit.attributes[index]);
  1633. });
  1634. attributes.filter(attr => attr.specified).map(attr => {
  1635. this.overlay.setAttribute(attr.name, attr.nodeValue);
  1636. });
  1637. this.overlay.style.fill = '#000000';
  1638. this.overlay.style.opacity = '0.4';
  1639. }
  1640. onLeftArrow() {
  1641. this.updateCurrentDataPoint(this.currentIndex - 1);
  1642. }
  1643. onRightArrow() {
  1644. this.updateCurrentDataPoint(this.currentIndex + 1);
  1645. }
  1646. set_avgUnitWidth_and_x_offset() {
  1647. this.avgUnitWidth = this.width/(this.xAxisLabels.length + 1);
  1648. this.x_offset = this.avgUnitWidth;
  1649. }
  1650. }
  1651. class LineChart extends AxisChart {
  1652. constructor(args) {
  1653. super(args);
  1654. this.xAxisMode = args.xAxisMode || 'span';
  1655. this.yAxisMode = args.yAxisMode || 'span';
  1656. if(args.hasOwnProperty('show_dots')) {
  1657. this.show_dots = args.show_dots;
  1658. } else {
  1659. this.show_dots = 1;
  1660. }
  1661. this.region_fill = args.region_fill;
  1662. if(Object.getPrototypeOf(this) !== LineChart.prototype) {
  1663. return;
  1664. }
  1665. this.dot_radius = args.dot_radius || 4;
  1666. this.heatline = args.heatline;
  1667. this.type = 'line';
  1668. this.setup();
  1669. }
  1670. setupPreUnitLayers() {
  1671. // Path groups
  1672. this.paths_groups = [];
  1673. this.y.map((d, i) => {
  1674. this.paths_groups[i] = makeSVGGroup(
  1675. this.drawArea,
  1676. 'path-group path-group-' + i
  1677. );
  1678. });
  1679. }
  1680. setup_values() {
  1681. super.setup_values();
  1682. this.unit_args = {
  1683. type: 'dot',
  1684. args: { radius: this.dot_radius }
  1685. };
  1686. }
  1687. makeDatasetUnits(x_values, y_values, color, dataset_index,
  1688. no_of_datasets, units_group, units_array, unit) {
  1689. if(this.show_dots) {
  1690. super.makeDatasetUnits(x_values, y_values, color, dataset_index,
  1691. no_of_datasets, units_group, units_array, unit);
  1692. }
  1693. }
  1694. make_paths() {
  1695. this.y.map(d => {
  1696. this.make_path(d, this.xPositions, d.yUnitPositions, d.color || this.colors[d.index]);
  1697. });
  1698. }
  1699. make_path(d, x_positions, y_positions, color) {
  1700. let points_list = y_positions.map((y, i) => (x_positions[i] + ',' + y));
  1701. let points_str = points_list.join("L");
  1702. this.paths_groups[d.index].textContent = '';
  1703. d.path = makePath("M"+points_str, 'line-graph-path', color);
  1704. this.paths_groups[d.index].appendChild(d.path);
  1705. if(this.heatline) {
  1706. let gradient_id = makeGradient(this.svg_defs, color);
  1707. d.path.style.stroke = `url(#${gradient_id})`;
  1708. }
  1709. if(this.region_fill) {
  1710. this.fill_region_for_dataset(d, color, points_str);
  1711. }
  1712. }
  1713. fill_region_for_dataset(d, color, points_str) {
  1714. let gradient_id = makeGradient(this.svg_defs, color, true);
  1715. let pathStr = "M" + `0,${this.zeroLine}L` + points_str + `L${this.width},${this.zeroLine}`;
  1716. d.regionPath = makePath(pathStr, `region-fill`, 'none', `url(#${gradient_id})`);
  1717. this.paths_groups[d.index].appendChild(d.regionPath);
  1718. }
  1719. }
  1720. class ScatterChart extends LineChart {
  1721. constructor(args) {
  1722. super(args);
  1723. this.type = 'scatter';
  1724. if(!args.dot_radius) {
  1725. this.dot_radius = 8;
  1726. } else {
  1727. this.dot_radius = args.dot_radius;
  1728. }
  1729. this.setup();
  1730. }
  1731. setup_values() {
  1732. super.setup_values();
  1733. this.unit_args = {
  1734. type: 'dot',
  1735. args: { radius: this.dot_radius }
  1736. };
  1737. }
  1738. make_paths() {}
  1739. make_path() {}
  1740. }
  1741. class PercentageChart extends BaseChart {
  1742. constructor(args) {
  1743. super(args);
  1744. this.type = 'percentage';
  1745. this.max_slices = 10;
  1746. this.max_legend_points = 6;
  1747. this.setup();
  1748. }
  1749. makeChartArea() {
  1750. this.chartWrapper.className += ' ' + 'graph-focus-margin';
  1751. this.chartWrapper.style.marginTop = '45px';
  1752. this.statsWrapper.className += ' ' + 'graph-focus-margin';
  1753. this.statsWrapper.style.marginBottom = '30px';
  1754. this.statsWrapper.style.paddingTop = '0px';
  1755. this.chartDiv = $.create('div', {
  1756. className: 'div',
  1757. inside: this.chartWrapper
  1758. });
  1759. this.chart = $.create('div', {
  1760. className: 'progress-chart',
  1761. inside: this.chartDiv
  1762. });
  1763. }
  1764. setupLayers() {
  1765. this.percentageBar = $.create('div', {
  1766. className: 'progress',
  1767. inside: this.chart
  1768. });
  1769. }
  1770. setup_values() {
  1771. this.slice_totals = [];
  1772. let all_totals = this.data.labels.map((d, i) => {
  1773. let total = 0;
  1774. this.data.datasets.map(e => {
  1775. total += e.values[i];
  1776. });
  1777. return [total, d];
  1778. }).filter(d => { return d[0] > 0; }); // keep only positive results
  1779. let totals = all_totals;
  1780. if(all_totals.length > this.max_slices) {
  1781. all_totals.sort((a, b) => { return b[0] - a[0]; });
  1782. totals = all_totals.slice(0, this.max_slices-1);
  1783. let others = all_totals.slice(this.max_slices-1);
  1784. let sum_of_others = 0;
  1785. others.map(d => {sum_of_others += d[0];});
  1786. totals.push([sum_of_others, 'Rest']);
  1787. this.colors[this.max_slices-1] = 'grey';
  1788. }
  1789. this.labels = [];
  1790. totals.map(d => {
  1791. this.slice_totals.push(d[0]);
  1792. this.labels.push(d[1]);
  1793. });
  1794. this.legend_totals = this.slice_totals.slice(0, this.max_legend_points);
  1795. }
  1796. renderComponents() {
  1797. this.grand_total = this.slice_totals.reduce((a, b) => a + b, 0);
  1798. this.slices = [];
  1799. this.slice_totals.map((total, i) => {
  1800. let slice = $.create('div', {
  1801. className: `progress-bar`,
  1802. inside: this.percentageBar,
  1803. styles: {
  1804. background: this.colors[i],
  1805. width: total*100/this.grand_total + "%"
  1806. }
  1807. });
  1808. this.slices.push(slice);
  1809. });
  1810. }
  1811. bindTooltip() {
  1812. this.slices.map((slice, i) => {
  1813. slice.addEventListener('mouseenter', () => {
  1814. let g_off = getOffset(this.chartWrapper), p_off = getOffset(slice);
  1815. let x = p_off.left - g_off.left + slice.offsetWidth/2;
  1816. let y = p_off.top - g_off.top - 6;
  1817. let title = (this.formatted_labels && this.formatted_labels.length>0
  1818. ? this.formatted_labels[i] : this.labels[i]) + ': ';
  1819. let percent = (this.slice_totals[i]*100/this.grand_total).toFixed(1);
  1820. this.tip.set_values(x, y, title, percent + "%");
  1821. this.tip.show_tip();
  1822. });
  1823. });
  1824. }
  1825. renderLegend() {
  1826. let x_values = this.formatted_labels && this.formatted_labels.length > 0
  1827. ? this.formatted_labels : this.labels;
  1828. this.legend_totals.map((d, i) => {
  1829. if(d) {
  1830. let stats = $.create('div', {
  1831. className: 'stats',
  1832. inside: this.statsWrapper
  1833. });
  1834. stats.innerHTML = `<span class="indicator">
  1835. <i style="background: ${this.colors[i]}"></i>
  1836. <span class="text-muted">${x_values[i]}:</span>
  1837. ${d}
  1838. </span>`;
  1839. }
  1840. });
  1841. }
  1842. }
  1843. const ANGLE_RATIO = Math.PI / 180;
  1844. const FULL_ANGLE = 360;
  1845. class PieChart extends BaseChart {
  1846. constructor(args) {
  1847. super(args);
  1848. this.type = 'pie';
  1849. this.elements_to_animate = null;
  1850. this.hoverRadio = args.hoverRadio || 0.1;
  1851. this.max_slices = 10;
  1852. this.max_legend_points = 6;
  1853. this.isAnimate = false;
  1854. this.startAngle = args.startAngle || 0;
  1855. this.clockWise = args.clockWise || false;
  1856. this.mouseMove = this.mouseMove.bind(this);
  1857. this.mouseLeave = this.mouseLeave.bind(this);
  1858. this.setup();
  1859. }
  1860. setup_values() {
  1861. this.centerX = this.width / 2;
  1862. this.centerY = this.height / 2;
  1863. this.radius = (this.height > this.width ? this.centerX : this.centerY);
  1864. this.slice_totals = [];
  1865. let all_totals = this.data.labels.map((d, i) => {
  1866. let total = 0;
  1867. this.data.datasets.map(e => {
  1868. total += e.values[i];
  1869. });
  1870. return [total, d];
  1871. }).filter(d => { return d[0] > 0; }); // keep only positive results
  1872. let totals = all_totals;
  1873. if(all_totals.length > this.max_slices) {
  1874. all_totals.sort((a, b) => { return b[0] - a[0]; });
  1875. totals = all_totals.slice(0, this.max_slices-1);
  1876. let others = all_totals.slice(this.max_slices-1);
  1877. let sum_of_others = 0;
  1878. others.map(d => {sum_of_others += d[0];});
  1879. totals.push([sum_of_others, 'Rest']);
  1880. this.colors[this.max_slices-1] = 'grey';
  1881. }
  1882. this.labels = [];
  1883. totals.map(d => {
  1884. this.slice_totals.push(d[0]);
  1885. this.labels.push(d[1]);
  1886. });
  1887. this.legend_totals = this.slice_totals.slice(0, this.max_legend_points);
  1888. }
  1889. static getPositionByAngle(angle,radius){
  1890. return {
  1891. x:Math.sin(angle * ANGLE_RATIO) * radius,
  1892. y:Math.cos(angle * ANGLE_RATIO) * radius,
  1893. };
  1894. }
  1895. makeArcPath(startPosition,endPosition){
  1896. const{centerX,centerY,radius,clockWise} = this;
  1897. 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`;
  1898. }
  1899. renderComponents(init){
  1900. const{radius,clockWise} = this;
  1901. this.grand_total = this.slice_totals.reduce((a, b) => a + b, 0);
  1902. const prevSlicesProperties = this.slicesProperties || [];
  1903. this.slices = [];
  1904. this.elements_to_animate = [];
  1905. this.slicesProperties = [];
  1906. let curAngle = 180 - this.startAngle;
  1907. this.slice_totals.map((total, i) => {
  1908. const startAngle = curAngle;
  1909. const originDiffAngle = (total / this.grand_total) * FULL_ANGLE;
  1910. const diffAngle = clockWise ? -originDiffAngle : originDiffAngle;
  1911. const endAngle = curAngle = curAngle + diffAngle;
  1912. const startPosition = PieChart.getPositionByAngle(startAngle,radius);
  1913. const endPosition = PieChart.getPositionByAngle(endAngle,radius);
  1914. const prevProperty = init && prevSlicesProperties[i];
  1915. let curStart,curEnd;
  1916. if(init){
  1917. curStart = prevProperty?prevProperty.startPosition : startPosition;
  1918. curEnd = prevProperty? prevProperty.endPosition : startPosition;
  1919. }else{
  1920. curStart = startPosition;
  1921. curEnd = endPosition;
  1922. }
  1923. const curPath = this.makeArcPath(curStart,curEnd);
  1924. let slice = makePath(curPath, 'pie-path', 'none', this.colors[i]);
  1925. slice.style.transition = 'transform .3s;';
  1926. this.drawArea.appendChild(slice);
  1927. this.slices.push(slice);
  1928. this.slicesProperties.push({
  1929. startPosition,
  1930. endPosition,
  1931. value: total,
  1932. total: this.grand_total,
  1933. startAngle,
  1934. endAngle,
  1935. angle:diffAngle
  1936. });
  1937. if(init){
  1938. this.elements_to_animate.push([{unit: slice, array: this.slices, index: this.slices.length - 1},
  1939. {d:this.makeArcPath(startPosition,endPosition)},
  1940. 650, "easein",null,{
  1941. d:curPath
  1942. }]);
  1943. }
  1944. });
  1945. if(init){
  1946. runSMILAnimation(this.chartWrapper, this.svg, this.elements_to_animate);
  1947. }
  1948. }
  1949. calTranslateByAngle(property){
  1950. const{radius,hoverRadio} = this;
  1951. const position = PieChart.getPositionByAngle(property.startAngle+(property.angle / 2),radius);
  1952. return `translate3d(${(position.x) * hoverRadio}px,${(position.y) * hoverRadio}px,0)`;
  1953. }
  1954. hoverSlice(path,i,flag,e){
  1955. if(!path) return;
  1956. const color = this.colors[i];
  1957. if(flag){
  1958. transform(path,this.calTranslateByAngle(this.slicesProperties[i]));
  1959. path.style.fill = lightenDarkenColor(color,50);
  1960. let g_off = getOffset(this.svg);
  1961. let x = e.pageX - g_off.left + 10;
  1962. let y = e.pageY - g_off.top - 10;
  1963. let title = (this.formatted_labels && this.formatted_labels.length>0
  1964. ? this.formatted_labels[i] : this.labels[i]) + ': ';
  1965. let percent = (this.slice_totals[i]*100/this.grand_total).toFixed(1);
  1966. this.tip.set_values(x, y, title, percent + "%");
  1967. this.tip.show_tip();
  1968. }else{
  1969. transform(path,'translate3d(0,0,0)');
  1970. this.tip.hide_tip();
  1971. path.style.fill = color;
  1972. }
  1973. }
  1974. mouseMove(e){
  1975. const target = e.target;
  1976. let prevIndex = this.curActiveSliceIndex;
  1977. let prevAcitve = this.curActiveSlice;
  1978. for(let i = 0; i < this.slices.length; i++){
  1979. if(target === this.slices[i]){
  1980. this.hoverSlice(prevAcitve,prevIndex,false);
  1981. this.curActiveSlice = target;
  1982. this.curActiveSliceIndex = i;
  1983. this.hoverSlice(target,i,true,e);
  1984. break;
  1985. }
  1986. }
  1987. }
  1988. mouseLeave(){
  1989. this.hoverSlice(this.curActiveSlice,this.curActiveSliceIndex,false);
  1990. }
  1991. bindTooltip() {
  1992. this.drawArea.addEventListener('mousemove',this.mouseMove);
  1993. this.drawArea.addEventListener('mouseleave',this.mouseLeave);
  1994. }
  1995. renderLegend() {
  1996. let x_values = this.formatted_labels && this.formatted_labels.length > 0
  1997. ? this.formatted_labels : this.labels;
  1998. this.legend_totals.map((d, i) => {
  1999. const color = this.colors[i];
  2000. if(d) {
  2001. let stats = $.create('div', {
  2002. className: 'stats',
  2003. inside: this.statsWrapper
  2004. });
  2005. stats.innerHTML = `<span class="indicator">
  2006. <i style="background-color:${color};"></i>
  2007. <span class="text-muted">${x_values[i]}:</span>
  2008. ${d}
  2009. </span>`;
  2010. }
  2011. });
  2012. }
  2013. }
  2014. // Playing around with dates
  2015. // https://stackoverflow.com/a/11252167/6495043
  2016. function treatAsUtc(dateStr) {
  2017. let result = new Date(dateStr);
  2018. result.setMinutes(result.getMinutes() - result.getTimezoneOffset());
  2019. return result;
  2020. }
  2021. function getDdMmYyyy(date) {
  2022. let dd = date.getDate();
  2023. let mm = date.getMonth() + 1; // getMonth() is zero-based
  2024. return [
  2025. (dd>9 ? '' : '0') + dd,
  2026. (mm>9 ? '' : '0') + mm,
  2027. date.getFullYear()
  2028. ].join('-');
  2029. }
  2030. function getWeeksBetween(startDateStr, endDateStr) {
  2031. return Math.ceil(getDaysBetween(startDateStr, endDateStr) / 7);
  2032. }
  2033. function getDaysBetween(startDateStr, endDateStr) {
  2034. let millisecondsPerDay = 24 * 60 * 60 * 1000;
  2035. return (treatAsUtc(endDateStr) - treatAsUtc(startDateStr)) / millisecondsPerDay;
  2036. }
  2037. // mutates
  2038. function addDays(date, numberOfDays) {
  2039. date.setDate(date.getDate() + numberOfDays);
  2040. }
  2041. // export function getMonthName() {}
  2042. class Heatmap extends BaseChart {
  2043. constructor({
  2044. start = '',
  2045. domain = '',
  2046. subdomain = '',
  2047. data = {},
  2048. discrete_domains = 0,
  2049. count_label = '',
  2050. legend_colors = []
  2051. }) {
  2052. super(arguments[0]);
  2053. this.type = 'heatmap';
  2054. this.domain = domain;
  2055. this.subdomain = subdomain;
  2056. this.data = data;
  2057. this.discrete_domains = discrete_domains;
  2058. this.count_label = count_label;
  2059. let today = new Date();
  2060. this.start = start || addDays(today, 365);
  2061. legend_colors = legend_colors.slice(0, 5);
  2062. this.legend_colors = this.validate_colors(legend_colors)
  2063. ? legend_colors
  2064. : ['#ebedf0', '#c6e48b', '#7bc96f', '#239a3b', '#196127'];
  2065. // Fixed 5-color theme,
  2066. // More colors are difficult to parse visually
  2067. this.distribution_size = 5;
  2068. this.translateX = 0;
  2069. // this.setup();
  2070. }
  2071. validate_colors(colors) {
  2072. if(colors.length < 5) return 0;
  2073. let valid = 1;
  2074. colors.forEach(function(string) {
  2075. if(!isValidColor(string)) {
  2076. valid = 0;
  2077. console.warn('"' + string + '" is not a valid color.');
  2078. }
  2079. }, this);
  2080. return valid;
  2081. }
  2082. setupConstants() {
  2083. this.today = new Date();
  2084. if(!this.start) {
  2085. this.start = new Date();
  2086. this.start.setFullYear( this.start.getFullYear() - 1 );
  2087. }
  2088. this.first_week_start = new Date(this.start.toDateString());
  2089. this.last_week_start = new Date(this.today.toDateString());
  2090. if(this.first_week_start.getDay() !== 7) {
  2091. addDays(this.first_week_start, (-1) * this.first_week_start.getDay());
  2092. }
  2093. if(this.last_week_start.getDay() !== 7) {
  2094. addDays(this.last_week_start, (-1) * this.last_week_start.getDay());
  2095. }
  2096. this.no_of_cols = getWeeksBetween(this.first_week_start + '', this.last_week_start + '') + 1;
  2097. }
  2098. calcWidth() {
  2099. this.baseWidth = (this.no_of_cols + 3) * 12 ;
  2100. if(this.discrete_domains) {
  2101. this.baseWidth += (12 * 12);
  2102. }
  2103. }
  2104. setupLayers() {
  2105. this.domain_label_group = this.makeLayer(
  2106. 'domain-label-group chart-label');
  2107. this.data_groups = this.makeLayer(
  2108. 'data-groups',
  2109. `translate(0, 20)`
  2110. );
  2111. }
  2112. setup_values() {
  2113. this.domain_label_group.textContent = '';
  2114. this.data_groups.textContent = '';
  2115. let data_values = Object.keys(this.data).map(key => this.data[key]);
  2116. this.distribution = calcDistribution(data_values, this.distribution_size);
  2117. this.month_names = ["January", "February", "March", "April", "May", "June",
  2118. "July", "August", "September", "October", "November", "December"
  2119. ];
  2120. this.render_all_weeks_and_store_x_values(this.no_of_cols);
  2121. }
  2122. render_all_weeks_and_store_x_values(no_of_weeks) {
  2123. let current_week_sunday = new Date(this.first_week_start);
  2124. this.week_col = 0;
  2125. this.current_month = current_week_sunday.getMonth();
  2126. this.months = [this.current_month + ''];
  2127. this.month_weeks = {}, this.month_start_points = [];
  2128. this.month_weeks[this.current_month] = 0;
  2129. this.month_start_points.push(13);
  2130. for(var i = 0; i < no_of_weeks; i++) {
  2131. let data_group, month_change = 0;
  2132. let day = new Date(current_week_sunday);
  2133. [data_group, month_change] = this.get_week_squares_group(day, this.week_col);
  2134. this.data_groups.appendChild(data_group);
  2135. this.week_col += 1 + parseInt(this.discrete_domains && month_change);
  2136. this.month_weeks[this.current_month]++;
  2137. if(month_change) {
  2138. this.current_month = (this.current_month + 1) % 12;
  2139. this.months.push(this.current_month + '');
  2140. this.month_weeks[this.current_month] = 1;
  2141. }
  2142. addDays(current_week_sunday, 7);
  2143. }
  2144. this.render_month_labels();
  2145. }
  2146. get_week_squares_group(current_date, index) {
  2147. const no_of_weekdays = 7;
  2148. const square_side = 10;
  2149. const cell_padding = 2;
  2150. const step = 1;
  2151. const today_time = this.today.getTime();
  2152. let month_change = 0;
  2153. let week_col_change = 0;
  2154. let data_group = makeSVGGroup(this.data_groups, 'data-group');
  2155. for(var y = 0, i = 0; i < no_of_weekdays; i += step, y += (square_side + cell_padding)) {
  2156. let data_value = 0;
  2157. let color_index = 0;
  2158. let current_timestamp = current_date.getTime()/1000;
  2159. let timestamp = Math.floor(current_timestamp - (current_timestamp % 86400)).toFixed(1);
  2160. if(this.data[timestamp]) {
  2161. data_value = this.data[timestamp];
  2162. }
  2163. if(this.data[Math.round(timestamp)]) {
  2164. data_value = this.data[Math.round(timestamp)];
  2165. }
  2166. if(data_value) {
  2167. color_index = getMaxCheckpoint(data_value, this.distribution);
  2168. }
  2169. let x = 13 + (index + week_col_change) * 12;
  2170. let dataAttr = {
  2171. 'data-date': getDdMmYyyy(current_date),
  2172. 'data-value': data_value,
  2173. 'data-day': current_date.getDay()
  2174. };
  2175. let heatSquare = makeHeatSquare('day', x, y, square_side,
  2176. this.legend_colors[color_index], dataAttr);
  2177. data_group.appendChild(heatSquare);
  2178. let next_date = new Date(current_date);
  2179. addDays(next_date, 1);
  2180. if(next_date.getTime() > today_time) break;
  2181. if(next_date.getMonth() - current_date.getMonth()) {
  2182. month_change = 1;
  2183. if(this.discrete_domains) {
  2184. week_col_change = 1;
  2185. }
  2186. this.month_start_points.push(13 + (index + week_col_change) * 12);
  2187. }
  2188. current_date = next_date;
  2189. }
  2190. return [data_group, month_change];
  2191. }
  2192. render_month_labels() {
  2193. // this.first_month_label = 1;
  2194. // if (this.first_week_start.getDate() > 8) {
  2195. // this.first_month_label = 0;
  2196. // }
  2197. // this.last_month_label = 1;
  2198. // let first_month = this.months.shift();
  2199. // let first_month_start = this.month_start_points.shift();
  2200. // render first month if
  2201. // let last_month = this.months.pop();
  2202. // let last_month_start = this.month_start_points.pop();
  2203. // render last month if
  2204. this.months.shift();
  2205. this.month_start_points.shift();
  2206. this.months.pop();
  2207. this.month_start_points.pop();
  2208. this.month_start_points.map((start, i) => {
  2209. let month_name = this.month_names[this.months[i]].substring(0, 3);
  2210. let text = makeText('y-value-text', start+12, 10, month_name);
  2211. this.domain_label_group.appendChild(text);
  2212. });
  2213. }
  2214. renderComponents() {
  2215. Array.prototype.slice.call(
  2216. this.container.querySelectorAll('.graph-stats-container, .sub-title, .title')
  2217. ).map(d => {
  2218. d.style.display = 'None';
  2219. });
  2220. this.chartWrapper.style.marginTop = '0px';
  2221. this.chartWrapper.style.paddingTop = '0px';
  2222. }
  2223. bindTooltip() {
  2224. Array.prototype.slice.call(
  2225. document.querySelectorAll(".data-group .day")
  2226. ).map(el => {
  2227. el.addEventListener('mouseenter', (e) => {
  2228. let count = e.target.getAttribute('data-value');
  2229. let date_parts = e.target.getAttribute('data-date').split('-');
  2230. let month = this.month_names[parseInt(date_parts[1])-1].substring(0, 3);
  2231. let g_off = this.chartWrapper.getBoundingClientRect(), p_off = e.target.getBoundingClientRect();
  2232. let width = parseInt(e.target.getAttribute('width'));
  2233. let x = p_off.left - g_off.left + (width+2)/2;
  2234. let y = p_off.top - g_off.top - (width+2)/2;
  2235. let value = count + ' ' + this.count_label;
  2236. let name = ' on ' + month + ' ' + date_parts[0] + ', ' + date_parts[2];
  2237. this.tip.set_values(x, y, name, value, [], 1);
  2238. this.tip.show_tip();
  2239. });
  2240. });
  2241. }
  2242. update(data) {
  2243. this.data = data;
  2244. this.setup_values();
  2245. this.bindTooltip();
  2246. }
  2247. }
  2248. const chartTypes = {
  2249. line: LineChart,
  2250. bar: BarChart,
  2251. scatter: ScatterChart,
  2252. percentage: PercentageChart,
  2253. heatmap: Heatmap,
  2254. pie: PieChart
  2255. };
  2256. function getChartByType(chartType = 'line', options) {
  2257. if (!chartTypes[chartType]) {
  2258. return new LineChart(options);
  2259. }
  2260. return new chartTypes[chartType](options);
  2261. }
  2262. class Chart {
  2263. constructor(args) {
  2264. return getChartByType(args.type, arguments[0]);
  2265. }
  2266. }
  2267. export default Chart;