Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.
 
 
 

3616 lignes
83 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. // https://css-tricks.com/snippets/javascript/loop-queryselectorall-matches/
  65. const ALL_CHART_TYPES = ['line', 'scatter', 'bar', 'percentage', 'heatmap', 'pie'];
  66. const COMPATIBLE_CHARTS = {
  67. bar: ['line', 'scatter', 'percentage', 'pie'],
  68. line: ['scatter', 'bar', 'percentage', 'pie'],
  69. pie: ['line', 'scatter', 'percentage', 'bar'],
  70. percentage: ['bar', 'line', 'scatter', 'pie'],
  71. heatmap: []
  72. };
  73. const DATA_COLOR_DIVISIONS = {
  74. bar: 'datasets',
  75. line: 'datasets',
  76. pie: 'labels',
  77. percentage: 'labels',
  78. heatmap: HEATMAP_DISTRIBUTION_SIZE
  79. };
  80. const BASE_CHART_TOP_MARGIN = 10;
  81. const BASE_CHART_LEFT_MARGIN = 20;
  82. const BASE_CHART_RIGHT_MARGIN = 20;
  83. const Y_AXIS_LEFT_MARGIN = 60;
  84. const Y_AXIS_RIGHT_MARGIN = 40;
  85. const INIT_CHART_UPDATE_TIMEOUT = 700;
  86. const CHART_POST_ANIMATE_TIMEOUT = 400;
  87. const DEFAULT_AXIS_CHART_TYPE = 'line';
  88. const AXIS_DATASET_CHART_TYPES = ['line', 'bar'];
  89. const AXIS_LEGEND_BAR_SIZE = 100;
  90. const BAR_CHART_SPACE_RATIO = 0.5;
  91. const MIN_BAR_PERCENT_HEIGHT = 0.01;
  92. const LINE_CHART_DOT_SIZE = 4;
  93. const DOT_OVERLAY_SIZE_INCR = 4;
  94. const PERCENTAGE_BAR_DEFAULT_HEIGHT = 20;
  95. const PERCENTAGE_BAR_DEFAULT_DEPTH = 2;
  96. // Fixed 5-color theme,
  97. // More colors are difficult to parse visually
  98. const HEATMAP_DISTRIBUTION_SIZE = 5;
  99. const HEATMAP_LEFT_MARGIN = 50;
  100. const HEATMAP_TOP_MARGIN = 25;
  101. const HEATMAP_SQUARE_SIZE = 10;
  102. const HEATMAP_GUTTER_SIZE = 2;
  103. const DEFAULT_CHAR_WIDTH = 7;
  104. const TOOLTIP_POINTER_TRIANGLE_HEIGHT = 5;
  105. const DEFAULT_CHART_COLORS = ['light-blue', 'blue', 'violet', 'red', 'orange',
  106. 'yellow', 'green', 'light-green', 'purple', 'magenta', 'light-grey', 'dark-grey'];
  107. const HEATMAP_COLORS_GREEN = ['#ebedf0', '#c6e48b', '#7bc96f', '#239a3b', '#196127'];
  108. const DEFAULT_COLORS = {
  109. bar: DEFAULT_CHART_COLORS,
  110. line: DEFAULT_CHART_COLORS,
  111. pie: DEFAULT_CHART_COLORS,
  112. percentage: DEFAULT_CHART_COLORS,
  113. heatmap: HEATMAP_COLORS_GREEN
  114. };
  115. // Universal constants
  116. const ANGLE_RATIO = Math.PI / 180;
  117. const FULL_ANGLE = 360;
  118. class SvgTip {
  119. constructor({
  120. parent = null,
  121. colors = []
  122. }) {
  123. this.parent = parent;
  124. this.colors = colors;
  125. this.titleName = '';
  126. this.titleValue = '';
  127. this.listValues = [];
  128. this.titleValueFirst = 0;
  129. this.x = 0;
  130. this.y = 0;
  131. this.top = 0;
  132. this.left = 0;
  133. this.setup();
  134. }
  135. setup() {
  136. this.makeTooltip();
  137. }
  138. refresh() {
  139. this.fill();
  140. this.calcPosition();
  141. }
  142. makeTooltip() {
  143. this.container = $.create('div', {
  144. inside: this.parent,
  145. className: 'graph-svg-tip comparison',
  146. innerHTML: `<span class="title"></span>
  147. <ul class="data-point-list"></ul>
  148. <div class="svg-pointer"></div>`
  149. });
  150. this.hideTip();
  151. this.title = this.container.querySelector('.title');
  152. this.dataPointList = this.container.querySelector('.data-point-list');
  153. this.parent.addEventListener('mouseleave', () => {
  154. this.hideTip();
  155. });
  156. }
  157. fill() {
  158. let title;
  159. if(this.index) {
  160. this.container.setAttribute('data-point-index', this.index);
  161. }
  162. if(this.titleValueFirst) {
  163. title = `<strong>${this.titleValue}</strong>${this.titleName}`;
  164. } else {
  165. title = `${this.titleName}<strong>${this.titleValue}</strong>`;
  166. }
  167. this.title.innerHTML = title;
  168. this.dataPointList.innerHTML = '';
  169. this.listValues.map((set, i) => {
  170. const color = this.colors[i] || 'black';
  171. let li = $.create('li', {
  172. styles: {
  173. 'border-top': `3px solid ${color}`
  174. },
  175. innerHTML: `<strong style="display: block;">${ set.value === 0 || set.value ? set.value : '' }</strong>
  176. ${set.title ? set.title : '' }`
  177. });
  178. this.dataPointList.appendChild(li);
  179. });
  180. }
  181. calcPosition() {
  182. let width = this.container.offsetWidth;
  183. this.top = this.y - this.container.offsetHeight
  184. - TOOLTIP_POINTER_TRIANGLE_HEIGHT;
  185. this.left = this.x - width/2;
  186. let maxLeft = this.parent.offsetWidth - width;
  187. let pointer = this.container.querySelector('.svg-pointer');
  188. if(this.left < 0) {
  189. pointer.style.left = `calc(50% - ${-1 * this.left}px)`;
  190. this.left = 0;
  191. } else if(this.left > maxLeft) {
  192. let delta = this.left - maxLeft;
  193. let pointerOffset = `calc(50% + ${delta}px)`;
  194. pointer.style.left = pointerOffset;
  195. this.left = maxLeft;
  196. } else {
  197. pointer.style.left = `50%`;
  198. }
  199. }
  200. setValues(x, y, title = {}, listValues = [], index = -1) {
  201. this.titleName = title.name;
  202. this.titleValue = title.value;
  203. this.listValues = listValues;
  204. this.x = x;
  205. this.y = y;
  206. this.titleValueFirst = title.valueFirst || 0;
  207. this.index = index;
  208. this.refresh();
  209. }
  210. hideTip() {
  211. this.container.style.top = '0px';
  212. this.container.style.left = '0px';
  213. this.container.style.opacity = '0';
  214. }
  215. showTip() {
  216. this.container.style.top = this.top + 'px';
  217. this.container.style.left = this.left + 'px';
  218. this.container.style.opacity = '1';
  219. }
  220. }
  221. function floatTwo(d) {
  222. return parseFloat(d.toFixed(2));
  223. }
  224. /**
  225. * Returns whether or not two given arrays are equal.
  226. * @param {Array} arr1 First array
  227. * @param {Array} arr2 Second array
  228. */
  229. /**
  230. * Shuffles array in place. ES6 version
  231. * @param {Array} array An array containing the items.
  232. */
  233. /**
  234. * Fill an array with extra points
  235. * @param {Array} array Array
  236. * @param {Number} count number of filler elements
  237. * @param {Object} element element to fill with
  238. * @param {Boolean} start fill at start?
  239. */
  240. function fillArray(array, count, element, start=false) {
  241. if(!element) {
  242. element = start ? array[0] : array[array.length - 1];
  243. }
  244. let fillerArray = new Array(Math.abs(count)).fill(element);
  245. array = start ? fillerArray.concat(array) : array.concat(fillerArray);
  246. return array;
  247. }
  248. /**
  249. * Returns pixel width of string.
  250. * @param {String} string
  251. * @param {Number} charWidth Width of single char in pixels
  252. */
  253. function getStringWidth(string, charWidth) {
  254. return (string+"").length * charWidth;
  255. }
  256. // https://stackoverflow.com/a/29325222
  257. function getPositionByAngle(angle, radius) {
  258. return {
  259. x: Math.sin(angle * ANGLE_RATIO) * radius,
  260. y: Math.cos(angle * ANGLE_RATIO) * radius,
  261. };
  262. }
  263. function getBarHeightAndYAttr(yTop, zeroLine) {
  264. let height, y;
  265. if (yTop <= zeroLine) {
  266. height = zeroLine - yTop;
  267. y = yTop;
  268. } else {
  269. height = yTop - zeroLine;
  270. y = zeroLine;
  271. }
  272. return [height, y];
  273. }
  274. function equilizeNoOfElements(array1, array2,
  275. extraCount = array2.length - array1.length) {
  276. // Doesn't work if either has zero elements.
  277. if(extraCount > 0) {
  278. array1 = fillArray(array1, extraCount);
  279. } else {
  280. array2 = fillArray(array2, extraCount);
  281. }
  282. return [array1, array2];
  283. }
  284. const PRESET_COLOR_MAP = {
  285. 'light-blue': '#7cd6fd',
  286. 'blue': '#5e64ff',
  287. 'violet': '#743ee2',
  288. 'red': '#ff5858',
  289. 'orange': '#ffa00a',
  290. 'yellow': '#feef72',
  291. 'green': '#28a745',
  292. 'light-green': '#98d85b',
  293. 'purple': '#b554ff',
  294. 'magenta': '#ffa3ef',
  295. 'black': '#36114C',
  296. 'grey': '#bdd3e6',
  297. 'light-grey': '#f0f4f7',
  298. 'dark-grey': '#b8c2cc'
  299. };
  300. function limitColor(r){
  301. if (r > 255) return 255;
  302. else if (r < 0) return 0;
  303. return r;
  304. }
  305. function lightenDarkenColor(color, amt) {
  306. let col = getColor(color);
  307. let usePound = false;
  308. if (col[0] == "#") {
  309. col = col.slice(1);
  310. usePound = true;
  311. }
  312. let num = parseInt(col,16);
  313. let r = limitColor((num >> 16) + amt);
  314. let b = limitColor(((num >> 8) & 0x00FF) + amt);
  315. let g = limitColor((num & 0x0000FF) + amt);
  316. return (usePound?"#":"") + (g | (b << 8) | (r << 16)).toString(16);
  317. }
  318. function isValidColor(string) {
  319. // https://stackoverflow.com/a/8027444/6495043
  320. return /(^#[0-9A-F]{6}$)|(^#[0-9A-F]{3}$)/i.test(string);
  321. }
  322. const getColor = (color) => {
  323. return PRESET_COLOR_MAP[color] || color;
  324. };
  325. const AXIS_TICK_LENGTH = 6;
  326. const LABEL_MARGIN = 4;
  327. const FONT_SIZE = 10;
  328. const BASE_LINE_COLOR = '#dadada';
  329. const FONT_FILL = '#555b51';
  330. function $$1(expr, con) {
  331. return typeof expr === "string"? (con || document).querySelector(expr) : expr || null;
  332. }
  333. function createSVG(tag, o) {
  334. var element = document.createElementNS("http://www.w3.org/2000/svg", tag);
  335. for (var i in o) {
  336. var val = o[i];
  337. if (i === "inside") {
  338. $$1(val).appendChild(element);
  339. }
  340. else if (i === "around") {
  341. var ref = $$1(val);
  342. ref.parentNode.insertBefore(element, ref);
  343. element.appendChild(ref);
  344. } else if (i === "styles") {
  345. if(typeof val === "object") {
  346. Object.keys(val).map(prop => {
  347. element.style[prop] = val[prop];
  348. });
  349. }
  350. } else {
  351. if(i === "className") { i = "class"; }
  352. if(i === "innerHTML") {
  353. element['textContent'] = val;
  354. } else {
  355. element.setAttribute(i, val);
  356. }
  357. }
  358. }
  359. return element;
  360. }
  361. function renderVerticalGradient(svgDefElem, gradientId) {
  362. return createSVG('linearGradient', {
  363. inside: svgDefElem,
  364. id: gradientId,
  365. x1: 0,
  366. x2: 0,
  367. y1: 0,
  368. y2: 1
  369. });
  370. }
  371. function setGradientStop(gradElem, offset, color, opacity) {
  372. return createSVG('stop', {
  373. 'inside': gradElem,
  374. 'style': `stop-color: ${color}`,
  375. 'offset': offset,
  376. 'stop-opacity': opacity
  377. });
  378. }
  379. function makeSVGContainer(parent, className, width, height) {
  380. return createSVG('svg', {
  381. className: className,
  382. inside: parent,
  383. width: width,
  384. height: height
  385. });
  386. }
  387. function makeSVGDefs(svgContainer) {
  388. return createSVG('defs', {
  389. inside: svgContainer,
  390. });
  391. }
  392. function makeSVGGroup(parent, className, transform='') {
  393. return createSVG('g', {
  394. className: className,
  395. inside: parent,
  396. transform: transform
  397. });
  398. }
  399. function makePath(pathStr, className='', stroke='none', fill='none') {
  400. return createSVG('path', {
  401. className: className,
  402. d: pathStr,
  403. styles: {
  404. stroke: stroke,
  405. fill: fill
  406. }
  407. });
  408. }
  409. function makeArcPathStr(startPosition, endPosition, center, radius, clockWise=1){
  410. let [arcStartX, arcStartY] = [center.x + startPosition.x, center.y + startPosition.y];
  411. let [arcEndX, arcEndY] = [center.x + endPosition.x, center.y + endPosition.y];
  412. return `M${center.x} ${center.y}
  413. L${arcStartX} ${arcStartY}
  414. A ${radius} ${radius} 0 0 ${clockWise ? 1 : 0}
  415. ${arcEndX} ${arcEndY} z`;
  416. }
  417. function makeGradient(svgDefElem, color, lighter = false) {
  418. let gradientId ='path-fill-gradient' + '-' + color + '-' +(lighter ? 'lighter' : 'default');
  419. let gradientDef = renderVerticalGradient(svgDefElem, gradientId);
  420. let opacities = [1, 0.6, 0.2];
  421. if(lighter) {
  422. opacities = [0.4, 0.2, 0];
  423. }
  424. setGradientStop(gradientDef, "0%", color, opacities[0]);
  425. setGradientStop(gradientDef, "50%", color, opacities[1]);
  426. setGradientStop(gradientDef, "100%", color, opacities[2]);
  427. return gradientId;
  428. }
  429. function percentageBar(x, y, width, height,
  430. depth=PERCENTAGE_BAR_DEFAULT_DEPTH, fill='none') {
  431. let args = {
  432. className: 'percentage-bar',
  433. x: x,
  434. y: y,
  435. width: width,
  436. height: height,
  437. fill: fill,
  438. styles: {
  439. 'stroke': lightenDarkenColor(fill, -25),
  440. // Diabolically good: https://stackoverflow.com/a/9000859
  441. // https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/stroke-dasharray
  442. 'stroke-dasharray': `0, ${height + width}, ${width}, ${height}`,
  443. 'stroke-width': depth
  444. },
  445. };
  446. return createSVG("rect", args);
  447. }
  448. function heatSquare(className, x, y, size, fill='none', data={}) {
  449. let args = {
  450. className: className,
  451. x: x,
  452. y: y,
  453. width: size,
  454. height: size,
  455. fill: fill
  456. };
  457. Object.keys(data).map(key => {
  458. args[key] = data[key];
  459. });
  460. return createSVG("rect", args);
  461. }
  462. function legendBar(x, y, size, fill='none', label) {
  463. let args = {
  464. className: 'legend-bar',
  465. x: 0,
  466. y: 0,
  467. width: size,
  468. height: '2px',
  469. fill: fill
  470. };
  471. let text = createSVG('text', {
  472. className: 'legend-dataset-text',
  473. x: 0,
  474. y: 0,
  475. dy: (FONT_SIZE * 2) + 'px',
  476. 'font-size': (FONT_SIZE * 1.2) + 'px',
  477. 'text-anchor': 'start',
  478. fill: FONT_FILL,
  479. innerHTML: label
  480. });
  481. let group = createSVG('g', {
  482. transform: `translate(${x}, ${y})`
  483. });
  484. group.appendChild(createSVG("rect", args));
  485. group.appendChild(text);
  486. return group;
  487. }
  488. function legendDot(x, y, size, fill='none', label) {
  489. let args = {
  490. className: 'legend-dot',
  491. cx: 0,
  492. cy: 0,
  493. r: size,
  494. fill: fill
  495. };
  496. let text = createSVG('text', {
  497. className: 'legend-dataset-text',
  498. x: 0,
  499. y: 0,
  500. dx: (FONT_SIZE) + 'px',
  501. dy: (FONT_SIZE/3) + 'px',
  502. 'font-size': (FONT_SIZE * 1.2) + 'px',
  503. 'text-anchor': 'start',
  504. fill: FONT_FILL,
  505. innerHTML: label
  506. });
  507. let group = createSVG('g', {
  508. transform: `translate(${x}, ${y})`
  509. });
  510. group.appendChild(createSVG("circle", args));
  511. group.appendChild(text);
  512. return group;
  513. }
  514. function makeText(className, x, y, content, options = {}) {
  515. let fontSize = options.fontSize || FONT_SIZE;
  516. let dy = options.dy !== undefined ? options.dy : (fontSize / 2);
  517. let fill = options.fill || FONT_FILL;
  518. let textAnchor = options.textAnchor || 'start';
  519. return createSVG('text', {
  520. className: className,
  521. x: x,
  522. y: y,
  523. dy: dy + 'px',
  524. 'font-size': fontSize + 'px',
  525. fill: fill,
  526. 'text-anchor': textAnchor,
  527. innerHTML: content
  528. });
  529. }
  530. function makeVertLine(x, label, y1, y2, options={}) {
  531. if(!options.stroke) options.stroke = BASE_LINE_COLOR;
  532. let l = createSVG('line', {
  533. className: 'line-vertical ' + options.className,
  534. x1: 0,
  535. x2: 0,
  536. y1: y1,
  537. y2: y2,
  538. styles: {
  539. stroke: options.stroke
  540. }
  541. });
  542. let text = createSVG('text', {
  543. x: 0,
  544. y: y1 > y2 ? y1 + LABEL_MARGIN : y1 - LABEL_MARGIN - FONT_SIZE,
  545. dy: FONT_SIZE + 'px',
  546. 'font-size': FONT_SIZE + 'px',
  547. 'text-anchor': 'middle',
  548. innerHTML: label + ""
  549. });
  550. let line = createSVG('g', {
  551. transform: `translate(${ x }, 0)`
  552. });
  553. line.appendChild(l);
  554. line.appendChild(text);
  555. return line;
  556. }
  557. function makeHoriLine(y, label, x1, x2, options={}) {
  558. if(!options.stroke) options.stroke = BASE_LINE_COLOR;
  559. if(!options.lineType) options.lineType = '';
  560. let className = 'line-horizontal ' + options.className +
  561. (options.lineType === "dashed" ? "dashed": "");
  562. let l = createSVG('line', {
  563. className: className,
  564. x1: x1,
  565. x2: x2,
  566. y1: 0,
  567. y2: 0,
  568. styles: {
  569. stroke: options.stroke
  570. }
  571. });
  572. let text = createSVG('text', {
  573. x: x1 < x2 ? x1 - LABEL_MARGIN : x1 + LABEL_MARGIN,
  574. y: 0,
  575. dy: (FONT_SIZE / 2 - 2) + 'px',
  576. 'font-size': FONT_SIZE + 'px',
  577. 'text-anchor': x1 < x2 ? 'end' : 'start',
  578. innerHTML: label+""
  579. });
  580. let line = createSVG('g', {
  581. transform: `translate(0, ${y})`,
  582. 'stroke-opacity': 1
  583. });
  584. if(text === 0 || text === '0') {
  585. line.style.stroke = "rgba(27, 31, 35, 0.6)";
  586. }
  587. line.appendChild(l);
  588. line.appendChild(text);
  589. return line;
  590. }
  591. function yLine(y, label, width, options={}) {
  592. if(!options.pos) options.pos = 'left';
  593. if(!options.offset) options.offset = 0;
  594. if(!options.mode) options.mode = 'span';
  595. if(!options.stroke) options.stroke = BASE_LINE_COLOR;
  596. if(!options.className) options.className = '';
  597. let x1 = -1 * AXIS_TICK_LENGTH;
  598. let x2 = options.mode === 'span' ? width + AXIS_TICK_LENGTH : 0;
  599. if(options.mode === 'tick' && options.pos === 'right') {
  600. x1 = width + AXIS_TICK_LENGTH;
  601. x2 = width;
  602. }
  603. // let offset = options.pos === 'left' ? -1 * options.offset : options.offset;
  604. x1 += options.offset;
  605. x2 += options.offset;
  606. return makeHoriLine(y, label, x1, x2, {
  607. stroke: options.stroke,
  608. className: options.className,
  609. lineType: options.lineType
  610. });
  611. }
  612. function xLine(x, label, height, options={}) {
  613. if(!options.pos) options.pos = 'bottom';
  614. if(!options.offset) options.offset = 0;
  615. if(!options.mode) options.mode = 'span';
  616. if(!options.stroke) options.stroke = BASE_LINE_COLOR;
  617. if(!options.className) options.className = '';
  618. // Draw X axis line in span/tick mode with optional label
  619. // y2(span)
  620. // |
  621. // |
  622. // x line |
  623. // |
  624. // |
  625. // ---------------------+-- y2(tick)
  626. // |
  627. // y1
  628. let y1 = height + AXIS_TICK_LENGTH;
  629. let y2 = options.mode === 'span' ? -1 * AXIS_TICK_LENGTH : height;
  630. if(options.mode === 'tick' && options.pos === 'top') {
  631. // top axis ticks
  632. y1 = -1 * AXIS_TICK_LENGTH;
  633. y2 = 0;
  634. }
  635. return makeVertLine(x, label, y1, y2, {
  636. stroke: options.stroke,
  637. className: options.className,
  638. lineType: options.lineType
  639. });
  640. }
  641. function yMarker(y, label, width, options={}) {
  642. let labelSvg = createSVG('text', {
  643. className: 'chart-label',
  644. x: width - getStringWidth(label, 5) - LABEL_MARGIN,
  645. y: 0,
  646. dy: (FONT_SIZE / -2) + 'px',
  647. 'font-size': FONT_SIZE + 'px',
  648. 'text-anchor': 'start',
  649. innerHTML: label+""
  650. });
  651. let line = makeHoriLine(y, '', 0, width, {
  652. stroke: options.stroke || BASE_LINE_COLOR,
  653. className: options.className || '',
  654. lineType: options.lineType
  655. });
  656. line.appendChild(labelSvg);
  657. return line;
  658. }
  659. function yRegion(y1, y2, width, label) {
  660. // return a group
  661. let height = y1 - y2;
  662. let rect = createSVG('rect', {
  663. className: `bar mini`, // remove class
  664. styles: {
  665. fill: `rgba(228, 234, 239, 0.49)`,
  666. stroke: BASE_LINE_COLOR,
  667. 'stroke-dasharray': `${width}, ${height}`
  668. },
  669. // 'data-point-index': index,
  670. x: 0,
  671. y: 0,
  672. width: width,
  673. height: height
  674. });
  675. let labelSvg = createSVG('text', {
  676. className: 'chart-label',
  677. x: width - getStringWidth(label+"", 4.5) - LABEL_MARGIN,
  678. y: 0,
  679. dy: (FONT_SIZE / -2) + 'px',
  680. 'font-size': FONT_SIZE + 'px',
  681. 'text-anchor': 'start',
  682. innerHTML: label+""
  683. });
  684. let region = createSVG('g', {
  685. transform: `translate(0, ${y2})`
  686. });
  687. region.appendChild(rect);
  688. region.appendChild(labelSvg);
  689. return region;
  690. }
  691. function datasetBar(x, yTop, width, color, label='', index=0, offset=0, meta={}) {
  692. let [height, y] = getBarHeightAndYAttr(yTop, meta.zeroLine);
  693. y -= offset;
  694. let rect = createSVG('rect', {
  695. className: `bar mini`,
  696. style: `fill: ${color}`,
  697. 'data-point-index': index,
  698. x: x,
  699. y: y,
  700. width: width,
  701. height: height || meta.minHeight // TODO: correct y for positive min height
  702. });
  703. label += "";
  704. if(!label && !label.length) {
  705. return rect;
  706. } else {
  707. rect.setAttribute('y', 0);
  708. rect.setAttribute('x', 0);
  709. let text = createSVG('text', {
  710. className: 'data-point-value',
  711. x: width/2,
  712. y: 0,
  713. dy: (FONT_SIZE / 2 * -1) + 'px',
  714. 'font-size': FONT_SIZE + 'px',
  715. 'text-anchor': 'middle',
  716. innerHTML: label
  717. });
  718. let group = createSVG('g', {
  719. 'data-point-index': index,
  720. transform: `translate(${x}, ${y})`
  721. });
  722. group.appendChild(rect);
  723. group.appendChild(text);
  724. return group;
  725. }
  726. }
  727. function datasetDot(x, y, radius, color, label='', index=0) {
  728. let dot = createSVG('circle', {
  729. style: `fill: ${color}`,
  730. 'data-point-index': index,
  731. cx: x,
  732. cy: y,
  733. r: radius
  734. });
  735. label += "";
  736. if(!label && !label.length) {
  737. return dot;
  738. } else {
  739. dot.setAttribute('cy', 0);
  740. dot.setAttribute('cx', 0);
  741. let text = createSVG('text', {
  742. className: 'data-point-value',
  743. x: 0,
  744. y: 0,
  745. dy: (FONT_SIZE / 2 * -1 - radius) + 'px',
  746. 'font-size': FONT_SIZE + 'px',
  747. 'text-anchor': 'middle',
  748. innerHTML: label
  749. });
  750. let group = createSVG('g', {
  751. 'data-point-index': index,
  752. transform: `translate(${x}, ${y})`
  753. });
  754. group.appendChild(dot);
  755. group.appendChild(text);
  756. return group;
  757. }
  758. }
  759. function getPaths(xList, yList, color, options={}, meta={}) {
  760. let pointsList = yList.map((y, i) => (xList[i] + ',' + y));
  761. let pointsStr = pointsList.join("L");
  762. let path = makePath("M"+pointsStr, 'line-graph-path', color);
  763. // HeatLine
  764. if(options.heatline) {
  765. let gradient_id = makeGradient(meta.svgDefs, color);
  766. path.style.stroke = `url(#${gradient_id})`;
  767. }
  768. let paths = {
  769. path: path
  770. };
  771. // Region
  772. if(options.regionFill) {
  773. let gradient_id_region = makeGradient(meta.svgDefs, color, true);
  774. // TODO: use zeroLine OR minimum
  775. let pathStr = "M" + `${xList[0]},${meta.zeroLine}L` + pointsStr + `L${xList.slice(-1)[0]},${meta.zeroLine}`;
  776. paths.region = makePath(pathStr, `region-fill`, 'none', `url(#${gradient_id_region})`);
  777. }
  778. return paths;
  779. }
  780. let makeOverlay = {
  781. 'bar': (unit) => {
  782. let transformValue;
  783. if(unit.nodeName !== 'rect') {
  784. transformValue = unit.getAttribute('transform');
  785. unit = unit.childNodes[0];
  786. }
  787. let overlay = unit.cloneNode();
  788. overlay.style.fill = '#000000';
  789. overlay.style.opacity = '0.4';
  790. if(transformValue) {
  791. overlay.setAttribute('transform', transformValue);
  792. }
  793. return overlay;
  794. },
  795. 'dot': (unit) => {
  796. let transformValue;
  797. if(unit.nodeName !== 'circle') {
  798. transformValue = unit.getAttribute('transform');
  799. unit = unit.childNodes[0];
  800. }
  801. let overlay = unit.cloneNode();
  802. let radius = unit.getAttribute('r');
  803. let fill = unit.getAttribute('fill');
  804. overlay.setAttribute('r', parseInt(radius) + DOT_OVERLAY_SIZE_INCR);
  805. overlay.setAttribute('fill', fill);
  806. overlay.style.opacity = '0.6';
  807. if(transformValue) {
  808. overlay.setAttribute('transform', transformValue);
  809. }
  810. return overlay;
  811. },
  812. 'heat_square': (unit) => {
  813. let transformValue;
  814. if(unit.nodeName !== 'circle') {
  815. transformValue = unit.getAttribute('transform');
  816. unit = unit.childNodes[0];
  817. }
  818. let overlay = unit.cloneNode();
  819. let radius = unit.getAttribute('r');
  820. let fill = unit.getAttribute('fill');
  821. overlay.setAttribute('r', parseInt(radius) + DOT_OVERLAY_SIZE_INCR);
  822. overlay.setAttribute('fill', fill);
  823. overlay.style.opacity = '0.6';
  824. if(transformValue) {
  825. overlay.setAttribute('transform', transformValue);
  826. }
  827. return overlay;
  828. }
  829. };
  830. let updateOverlay = {
  831. 'bar': (unit, overlay) => {
  832. let transformValue;
  833. if(unit.nodeName !== 'rect') {
  834. transformValue = unit.getAttribute('transform');
  835. unit = unit.childNodes[0];
  836. }
  837. let attributes = ['x', 'y', 'width', 'height'];
  838. Object.values(unit.attributes)
  839. .filter(attr => attributes.includes(attr.name) && attr.specified)
  840. .map(attr => {
  841. overlay.setAttribute(attr.name, attr.nodeValue);
  842. });
  843. if(transformValue) {
  844. overlay.setAttribute('transform', transformValue);
  845. }
  846. },
  847. 'dot': (unit, overlay) => {
  848. let transformValue;
  849. if(unit.nodeName !== 'circle') {
  850. transformValue = unit.getAttribute('transform');
  851. unit = unit.childNodes[0];
  852. }
  853. let attributes = ['cx', 'cy'];
  854. Object.values(unit.attributes)
  855. .filter(attr => attributes.includes(attr.name) && attr.specified)
  856. .map(attr => {
  857. overlay.setAttribute(attr.name, attr.nodeValue);
  858. });
  859. if(transformValue) {
  860. overlay.setAttribute('transform', transformValue);
  861. }
  862. },
  863. 'heat_square': (unit, overlay) => {
  864. let transformValue;
  865. if(unit.nodeName !== 'circle') {
  866. transformValue = unit.getAttribute('transform');
  867. unit = unit.childNodes[0];
  868. }
  869. let attributes = ['cx', 'cy'];
  870. Object.values(unit.attributes)
  871. .filter(attr => attributes.includes(attr.name) && attr.specified)
  872. .map(attr => {
  873. overlay.setAttribute(attr.name, attr.nodeValue);
  874. });
  875. if(transformValue) {
  876. overlay.setAttribute('transform', transformValue);
  877. }
  878. },
  879. };
  880. const UNIT_ANIM_DUR = 350;
  881. const PATH_ANIM_DUR = 350;
  882. const MARKER_LINE_ANIM_DUR = UNIT_ANIM_DUR;
  883. const REPLACE_ALL_NEW_DUR = 250;
  884. const STD_EASING = 'easein';
  885. function translate(unit, oldCoord, newCoord, duration) {
  886. let old = typeof oldCoord === 'string' ? oldCoord : oldCoord.join(', ');
  887. return [
  888. unit,
  889. {transform: newCoord.join(', ')},
  890. duration,
  891. STD_EASING,
  892. "translate",
  893. {transform: old}
  894. ];
  895. }
  896. function translateVertLine(xLine, newX, oldX) {
  897. return translate(xLine, [oldX, 0], [newX, 0], MARKER_LINE_ANIM_DUR);
  898. }
  899. function translateHoriLine(yLine, newY, oldY) {
  900. return translate(yLine, [0, oldY], [0, newY], MARKER_LINE_ANIM_DUR);
  901. }
  902. function animateRegion(rectGroup, newY1, newY2, oldY2) {
  903. let newHeight = newY1 - newY2;
  904. let rect = rectGroup.childNodes[0];
  905. let width = rect.getAttribute("width");
  906. let rectAnim = [
  907. rect,
  908. { height: newHeight, 'stroke-dasharray': `${width}, ${newHeight}` },
  909. MARKER_LINE_ANIM_DUR,
  910. STD_EASING
  911. ];
  912. let groupAnim = translate(rectGroup, [0, oldY2], [0, newY2], MARKER_LINE_ANIM_DUR);
  913. return [rectAnim, groupAnim];
  914. }
  915. function animateBar(bar, x, yTop, width, offset=0, meta={}) {
  916. let [height, y] = getBarHeightAndYAttr(yTop, meta.zeroLine);
  917. y -= offset;
  918. if(bar.nodeName !== 'rect') {
  919. let rect = bar.childNodes[0];
  920. let rectAnim = [
  921. rect,
  922. {width: width, height: height},
  923. UNIT_ANIM_DUR,
  924. STD_EASING
  925. ];
  926. let oldCoordStr = bar.getAttribute("transform").split("(")[1].slice(0, -1);
  927. let groupAnim = translate(bar, oldCoordStr, [x, y], MARKER_LINE_ANIM_DUR);
  928. return [rectAnim, groupAnim];
  929. } else {
  930. return [[bar, {width: width, height: height, x: x, y: y}, UNIT_ANIM_DUR, STD_EASING]];
  931. }
  932. // bar.animate({height: args.newHeight, y: yTop}, UNIT_ANIM_DUR, mina.easein);
  933. }
  934. function animateDot(dot, x, y) {
  935. if(dot.nodeName !== 'circle') {
  936. let oldCoordStr = dot.getAttribute("transform").split("(")[1].slice(0, -1);
  937. let groupAnim = translate(dot, oldCoordStr, [x, y], MARKER_LINE_ANIM_DUR);
  938. return [groupAnim];
  939. } else {
  940. return [[dot, {cx: x, cy: y}, UNIT_ANIM_DUR, STD_EASING]];
  941. }
  942. // dot.animate({cy: yTop}, UNIT_ANIM_DUR, mina.easein);
  943. }
  944. function animatePath(paths, newXList, newYList, zeroLine) {
  945. let pathComponents = [];
  946. let pointsStr = newYList.map((y, i) => (newXList[i] + ',' + y));
  947. let pathStr = pointsStr.join("L");
  948. const animPath = [paths.path, {d:"M"+pathStr}, PATH_ANIM_DUR, STD_EASING];
  949. pathComponents.push(animPath);
  950. if(paths.region) {
  951. let regStartPt = `${newXList[0]},${zeroLine}L`;
  952. let regEndPt = `L${newXList.slice(-1)[0]}, ${zeroLine}`;
  953. const animRegion = [
  954. paths.region,
  955. {d:"M" + regStartPt + pathStr + regEndPt},
  956. PATH_ANIM_DUR,
  957. STD_EASING
  958. ];
  959. pathComponents.push(animRegion);
  960. }
  961. return pathComponents;
  962. }
  963. function animatePathStr(oldPath, pathStr) {
  964. return [oldPath, {d: pathStr}, UNIT_ANIM_DUR, STD_EASING];
  965. }
  966. // Leveraging SMIL Animations
  967. const EASING = {
  968. ease: "0.25 0.1 0.25 1",
  969. linear: "0 0 1 1",
  970. // easein: "0.42 0 1 1",
  971. easein: "0.1 0.8 0.2 1",
  972. easeout: "0 0 0.58 1",
  973. easeinout: "0.42 0 0.58 1"
  974. };
  975. function animateSVGElement(element, props, dur, easingType="linear", type=undefined, oldValues={}) {
  976. let animElement = element.cloneNode(true);
  977. let newElement = element.cloneNode(true);
  978. for(var attributeName in props) {
  979. let animateElement;
  980. if(attributeName === 'transform') {
  981. animateElement = document.createElementNS("http://www.w3.org/2000/svg", "animateTransform");
  982. } else {
  983. animateElement = document.createElementNS("http://www.w3.org/2000/svg", "animate");
  984. }
  985. let currentValue = oldValues[attributeName] || element.getAttribute(attributeName);
  986. let value = props[attributeName];
  987. let animAttr = {
  988. attributeName: attributeName,
  989. from: currentValue,
  990. to: value,
  991. begin: "0s",
  992. dur: dur/1000 + "s",
  993. values: currentValue + ";" + value,
  994. keySplines: EASING[easingType],
  995. keyTimes: "0;1",
  996. calcMode: "spline",
  997. fill: 'freeze'
  998. };
  999. if(type) {
  1000. animAttr["type"] = type;
  1001. }
  1002. for (var i in animAttr) {
  1003. animateElement.setAttribute(i, animAttr[i]);
  1004. }
  1005. animElement.appendChild(animateElement);
  1006. if(type) {
  1007. newElement.setAttribute(attributeName, `translate(${value})`);
  1008. } else {
  1009. newElement.setAttribute(attributeName, value);
  1010. }
  1011. }
  1012. return [animElement, newElement];
  1013. }
  1014. function transform(element, style) { // eslint-disable-line no-unused-vars
  1015. element.style.transform = style;
  1016. element.style.webkitTransform = style;
  1017. element.style.msTransform = style;
  1018. element.style.mozTransform = style;
  1019. element.style.oTransform = style;
  1020. }
  1021. function animateSVG(svgContainer, elements) {
  1022. let newElements = [];
  1023. let animElements = [];
  1024. elements.map(element => {
  1025. let unit = element[0];
  1026. let parent = unit.parentNode;
  1027. let animElement, newElement;
  1028. element[0] = unit;
  1029. [animElement, newElement] = animateSVGElement(...element);
  1030. newElements.push(newElement);
  1031. animElements.push([animElement, parent]);
  1032. parent.replaceChild(animElement, unit);
  1033. });
  1034. let animSvg = svgContainer.cloneNode(true);
  1035. animElements.map((animElement, i) => {
  1036. animElement[1].replaceChild(newElements[i], animElement[0]);
  1037. elements[i][0] = newElements[i];
  1038. });
  1039. return animSvg;
  1040. }
  1041. function runSMILAnimation(parent, svgElement, elementsToAnimate) {
  1042. if(elementsToAnimate.length === 0) return;
  1043. let animSvgElement = animateSVG(svgElement, elementsToAnimate);
  1044. if(svgElement.parentNode == parent) {
  1045. parent.removeChild(svgElement);
  1046. parent.appendChild(animSvgElement);
  1047. }
  1048. // Replace the new svgElement (data has already been replaced)
  1049. setTimeout(() => {
  1050. if(animSvgElement.parentNode == parent) {
  1051. parent.removeChild(animSvgElement);
  1052. parent.appendChild(svgElement);
  1053. }
  1054. }, REPLACE_ALL_NEW_DUR);
  1055. }
  1056. class BaseChart {
  1057. constructor(parent, options) {
  1058. this.parent = typeof parent === 'string'
  1059. ? document.querySelector(parent)
  1060. : parent;
  1061. if (!(this.parent instanceof HTMLElement)) {
  1062. throw new Error('No `parent` element to render on was provided.');
  1063. }
  1064. this.rawChartArgs = options;
  1065. this.title = options.title || '';
  1066. this.argHeight = options.height || 240;
  1067. this.type = options.type || '';
  1068. this.realData = this.prepareData(options.data);
  1069. this.data = this.prepareFirstData(this.realData);
  1070. this.colors = this.validateColors(options.colors, this.type);
  1071. this.config = {
  1072. showTooltip: 1, // calculate
  1073. showLegend: options.showLegend || 1,
  1074. isNavigable: options.isNavigable || 0,
  1075. animate: 1
  1076. };
  1077. this.state = {};
  1078. this.options = {};
  1079. this.initTimeout = INIT_CHART_UPDATE_TIMEOUT;
  1080. if(this.config.isNavigable) {
  1081. this.overlays = [];
  1082. }
  1083. this.configure(options);
  1084. }
  1085. configure() {
  1086. this.setMargins();
  1087. // Bind window events
  1088. window.addEventListener('resize', () => this.draw(true));
  1089. window.addEventListener('orientationchange', () => this.draw(true));
  1090. }
  1091. validateColors(colors, type) {
  1092. const validColors = [];
  1093. colors = (colors || []).concat(DEFAULT_COLORS[type]);
  1094. colors.forEach((string) => {
  1095. const color = getColor(string);
  1096. if(!isValidColor(color)) {
  1097. console.warn('"' + string + '" is not a valid color.');
  1098. } else {
  1099. validColors.push(color);
  1100. }
  1101. });
  1102. return validColors;
  1103. }
  1104. setMargins() {
  1105. let height = this.argHeight;
  1106. this.baseHeight = height;
  1107. this.height = height - 70;
  1108. this.topMargin = BASE_CHART_TOP_MARGIN;
  1109. // Horizontal margins
  1110. this.leftMargin = BASE_CHART_LEFT_MARGIN;
  1111. this.rightMargin = BASE_CHART_RIGHT_MARGIN;
  1112. }
  1113. setup() {
  1114. this.makeContainer();
  1115. this.updateWidth();
  1116. this.makeTooltip();
  1117. this.draw(false, true);
  1118. }
  1119. setupComponents() {
  1120. this.components = new Map();
  1121. }
  1122. makeContainer() {
  1123. // Chart needs a dedicated parent element
  1124. this.parent.innerHTML = '';
  1125. this.container = $.create('div', {
  1126. inside: this.parent,
  1127. className: 'chart-container'
  1128. });
  1129. }
  1130. makeTooltip() {
  1131. this.tip = new SvgTip({
  1132. parent: this.container,
  1133. colors: this.colors
  1134. });
  1135. this.bindTooltip();
  1136. }
  1137. bindTooltip() {}
  1138. draw(onlyWidthChange=false, init=false) {
  1139. this.calc(onlyWidthChange);
  1140. this.updateWidth();
  1141. this.makeChartArea();
  1142. this.setupComponents();
  1143. this.components.forEach(c => c.setup(this.drawArea));
  1144. // this.components.forEach(c => c.make());
  1145. this.render(this.components, false);
  1146. if(init) {
  1147. this.data = this.realData;
  1148. setTimeout(() => {this.update(this.data);}, this.initTimeout);
  1149. }
  1150. this.renderLegend();
  1151. this.setupNavigation(init);
  1152. }
  1153. updateWidth() {
  1154. this.baseWidth = getElementContentWidth(this.parent);
  1155. this.width = this.baseWidth - (this.leftMargin + this.rightMargin);
  1156. }
  1157. update(data) {
  1158. if(!data) {
  1159. console.error('No data to update.');
  1160. }
  1161. this.data = this.prepareData(data);
  1162. this.calc(); // builds state
  1163. this.render();
  1164. }
  1165. prepareData(data=this.data) {
  1166. return data;
  1167. }
  1168. prepareFirstData(data=this.data) {
  1169. return data;
  1170. }
  1171. calc() {} // builds state
  1172. render(components=this.components, animate=true) {
  1173. if(this.config.isNavigable) {
  1174. // Remove all existing overlays
  1175. this.overlays.map(o => o.parentNode.removeChild(o));
  1176. // ref.parentNode.insertBefore(element, ref);
  1177. }
  1178. let elementsToAnimate = [];
  1179. // Can decouple to this.refreshComponents() first to save animation timeout
  1180. components.forEach(c => {
  1181. elementsToAnimate = elementsToAnimate.concat(c.update(animate));
  1182. });
  1183. if(elementsToAnimate.length > 0) {
  1184. runSMILAnimation(this.container, this.svg, elementsToAnimate);
  1185. setTimeout(() => {
  1186. components.forEach(c => c.make());
  1187. this.updateNav();
  1188. }, CHART_POST_ANIMATE_TIMEOUT);
  1189. } else {
  1190. components.forEach(c => c.make());
  1191. this.updateNav();
  1192. }
  1193. }
  1194. updateNav() {
  1195. if(this.config.isNavigable) {
  1196. this.makeOverlay();
  1197. this.bindUnits();
  1198. }
  1199. }
  1200. makeChartArea() {
  1201. if(this.svg) {
  1202. this.container.removeChild(this.svg);
  1203. }
  1204. let titleAreaHeight = 0;
  1205. let legendAreaHeight = 0;
  1206. if(this.title.length) {
  1207. titleAreaHeight = 40;
  1208. }
  1209. if(this.config.showLegend) {
  1210. legendAreaHeight = 30;
  1211. }
  1212. this.svg = makeSVGContainer(
  1213. this.container,
  1214. 'frappe-chart chart',
  1215. this.baseWidth,
  1216. this.baseHeight + titleAreaHeight + legendAreaHeight
  1217. );
  1218. this.svgDefs = makeSVGDefs(this.svg);
  1219. // console.log(this.baseHeight, titleAreaHeight, legendAreaHeight);
  1220. if(this.title.length) {
  1221. this.titleEL = makeText(
  1222. 'title',
  1223. this.leftMargin - AXIS_TICK_LENGTH * 6,
  1224. this.topMargin,
  1225. this.title,
  1226. {
  1227. fontSize: 12,
  1228. fill: '#666666'
  1229. }
  1230. );
  1231. this.svg.appendChild(this.titleEL);
  1232. }
  1233. let top = this.topMargin + titleAreaHeight;
  1234. this.drawArea = makeSVGGroup(
  1235. this.svg,
  1236. this.type + '-chart',
  1237. `translate(${this.leftMargin}, ${top})`
  1238. );
  1239. top = this.baseHeight - titleAreaHeight;
  1240. this.legendArea = makeSVGGroup(
  1241. this.svg,
  1242. 'chart-legend',
  1243. `translate(${this.leftMargin}, ${top})`
  1244. );
  1245. this.updateTipOffset(this.leftMargin, this.topMargin + titleAreaHeight);
  1246. }
  1247. updateTipOffset(x, y) {
  1248. this.tip.offset = {
  1249. x: x,
  1250. y: y
  1251. };
  1252. }
  1253. renderLegend() {}
  1254. setupNavigation(init=false) {
  1255. if(!this.config.isNavigable) return;
  1256. if(init) {
  1257. this.bindOverlay();
  1258. this.keyActions = {
  1259. '13': this.onEnterKey.bind(this),
  1260. '37': this.onLeftArrow.bind(this),
  1261. '38': this.onUpArrow.bind(this),
  1262. '39': this.onRightArrow.bind(this),
  1263. '40': this.onDownArrow.bind(this),
  1264. };
  1265. document.addEventListener('keydown', (e) => {
  1266. if(isElementInViewport(this.container)) {
  1267. e = e || window.event;
  1268. if(this.keyActions[e.keyCode]) {
  1269. this.keyActions[e.keyCode]();
  1270. }
  1271. }
  1272. });
  1273. }
  1274. }
  1275. makeOverlay() {}
  1276. updateOverlay() {}
  1277. bindOverlay() {}
  1278. bindUnits() {}
  1279. onLeftArrow() {}
  1280. onRightArrow() {}
  1281. onUpArrow() {}
  1282. onDownArrow() {}
  1283. onEnterKey() {}
  1284. addDataPoint() {}
  1285. removeDataPoint() {}
  1286. getDataPoint() {}
  1287. setCurrentDataPoint() {}
  1288. updateDataset() {}
  1289. getDifferentChart(type) {
  1290. const currentType = this.type;
  1291. let args = this.rawChartArgs;
  1292. if(type === currentType) return;
  1293. if(!ALL_CHART_TYPES.includes(type)) {
  1294. console.error(`'${type}' is not a valid chart type.`);
  1295. }
  1296. if(!COMPATIBLE_CHARTS[currentType].includes(type)) {
  1297. console.error(`'${currentType}' chart cannot be converted to a '${type}' chart.`);
  1298. }
  1299. // whether the new chart can use the existing colors
  1300. const useColor = DATA_COLOR_DIVISIONS[currentType] === DATA_COLOR_DIVISIONS[type];
  1301. // Okay, this is anticlimactic
  1302. // this function will need to actually be 'changeChartType(type)'
  1303. // that will update only the required elements, but for now ...
  1304. args.type = type;
  1305. args.colors = useColor ? args.colors : undefined;
  1306. return new Chart(this.parent, args);
  1307. }
  1308. unbindWindowEvents(){
  1309. window.removeEventListener('resize', () => this.draw(true));
  1310. window.removeEventListener('orientationchange', () => this.draw(true));
  1311. }
  1312. }
  1313. class AggregationChart extends BaseChart {
  1314. constructor(parent, args) {
  1315. super(parent, args);
  1316. }
  1317. configure(args) {
  1318. super.configure(args);
  1319. this.config.maxSlices = args.maxSlices || 20;
  1320. this.config.maxLegendPoints = args.maxLegendPoints || 20;
  1321. }
  1322. calc() {
  1323. let s = this.state;
  1324. let maxSlices = this.config.maxSlices;
  1325. s.sliceTotals = [];
  1326. let allTotals = this.data.labels.map((label, i) => {
  1327. let total = 0;
  1328. this.data.datasets.map(e => {
  1329. total += e.values[i];
  1330. });
  1331. return [total, label];
  1332. }).filter(d => { return d[0] > 0; }); // keep only positive results
  1333. let totals = allTotals;
  1334. if(allTotals.length > maxSlices) {
  1335. // Prune and keep a grey area for rest as per maxSlices
  1336. allTotals.sort((a, b) => { return b[0] - a[0]; });
  1337. totals = allTotals.slice(0, maxSlices-1);
  1338. let remaining = allTotals.slice(maxSlices-1);
  1339. let sumOfRemaining = 0;
  1340. remaining.map(d => {sumOfRemaining += d[0];});
  1341. totals.push([sumOfRemaining, 'Rest']);
  1342. this.colors[maxSlices-1] = 'grey';
  1343. }
  1344. s.labels = [];
  1345. totals.map(d => {
  1346. s.sliceTotals.push(d[0]);
  1347. s.labels.push(d[1]);
  1348. });
  1349. s.grandTotal = s.sliceTotals.reduce((a, b) => a + b, 0);
  1350. this.center = {
  1351. x: this.width / 2,
  1352. y: this.height / 2
  1353. };
  1354. }
  1355. renderLegend() {
  1356. let s = this.state;
  1357. this.legendArea.textContent = '';
  1358. this.legendTotals = s.sliceTotals.slice(0, this.config.maxLegendPoints);
  1359. this.legendTotals.map((d, i) => {
  1360. let barWidth = 110;
  1361. let rect = legendDot(
  1362. barWidth * i + 5,
  1363. '0',
  1364. 5,
  1365. this.colors[i],
  1366. `${s.labels[i]}: ${d}`
  1367. );
  1368. this.legendArea.appendChild(rect);
  1369. });
  1370. }
  1371. }
  1372. // Playing around with dates
  1373. const NO_OF_YEAR_MONTHS = 12;
  1374. const NO_OF_DAYS_IN_WEEK = 7;
  1375. const NO_OF_MILLIS = 1000;
  1376. const SEC_IN_DAY = 86400;
  1377. const MONTH_NAMES = ["January", "February", "March", "April", "May", "June",
  1378. "July", "August", "September", "October", "November", "December"];
  1379. const DAY_NAMES_SHORT = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
  1380. // https://stackoverflow.com/a/11252167/6495043
  1381. function treatAsUtc(date) {
  1382. let result = new Date(date);
  1383. result.setMinutes(result.getMinutes() - result.getTimezoneOffset());
  1384. return result;
  1385. }
  1386. function getYyyyMmDd(date) {
  1387. let dd = date.getDate();
  1388. let mm = date.getMonth() + 1; // getMonth() is zero-based
  1389. return [
  1390. date.getFullYear(),
  1391. (mm>9 ? '' : '0') + mm,
  1392. (dd>9 ? '' : '0') + dd
  1393. ].join('-');
  1394. }
  1395. function clone(date) {
  1396. return new Date(date.getTime());
  1397. }
  1398. // export function getMonthsBetween(startDate, endDate) {}
  1399. function getWeeksBetween(startDate, endDate) {
  1400. let weekStartDate = setDayToSunday(startDate);
  1401. return Math.ceil(getDaysBetween(weekStartDate, endDate) / NO_OF_DAYS_IN_WEEK);
  1402. }
  1403. function getDaysBetween(startDate, endDate) {
  1404. let millisecondsPerDay = SEC_IN_DAY * NO_OF_MILLIS;
  1405. return (treatAsUtc(endDate) - treatAsUtc(startDate)) / millisecondsPerDay;
  1406. }
  1407. function areInSameMonth(startDate, endDate) {
  1408. return startDate.getMonth() === endDate.getMonth()
  1409. && startDate.getFullYear() === endDate.getFullYear();
  1410. }
  1411. function getMonthName(i, short=false) {
  1412. let monthName = MONTH_NAMES[i];
  1413. return short ? monthName.slice(0, 3) : monthName;
  1414. }
  1415. function getLastDateInMonth (month, year) {
  1416. return new Date(year, month + 1, 0); // 0: last day in previous month
  1417. }
  1418. // mutates
  1419. function setDayToSunday(date) {
  1420. let newDate = clone(date);
  1421. const day = newDate.getDay();
  1422. if(day !== 0) {
  1423. addDays(newDate, (-1) * day);
  1424. }
  1425. return newDate;
  1426. }
  1427. // mutates
  1428. function addDays(date, numberOfDays) {
  1429. date.setDate(date.getDate() + numberOfDays);
  1430. }
  1431. class ChartComponent {
  1432. constructor({
  1433. layerClass = '',
  1434. layerTransform = '',
  1435. constants,
  1436. getData,
  1437. makeElements,
  1438. animateElements
  1439. }) {
  1440. this.layerTransform = layerTransform;
  1441. this.constants = constants;
  1442. this.makeElements = makeElements;
  1443. this.getData = getData;
  1444. this.animateElements = animateElements;
  1445. this.store = [];
  1446. this.labels = [];
  1447. this.layerClass = layerClass;
  1448. this.layerClass = typeof(this.layerClass) === 'function'
  1449. ? this.layerClass() : this.layerClass;
  1450. this.refresh();
  1451. }
  1452. refresh(data) {
  1453. this.data = data || this.getData();
  1454. }
  1455. setup(parent) {
  1456. this.layer = makeSVGGroup(parent, this.layerClass, this.layerTransform);
  1457. }
  1458. make() {
  1459. this.render(this.data);
  1460. this.oldData = this.data;
  1461. }
  1462. render(data) {
  1463. this.store = this.makeElements(data);
  1464. this.layer.textContent = '';
  1465. this.store.forEach(element => {
  1466. this.layer.appendChild(element);
  1467. });
  1468. this.labels.forEach(element => {
  1469. this.layer.appendChild(element);
  1470. });
  1471. }
  1472. update(animate = true) {
  1473. this.refresh();
  1474. let animateElements = [];
  1475. if(animate) {
  1476. animateElements = this.animateElements(this.data) || [];
  1477. }
  1478. return animateElements;
  1479. }
  1480. }
  1481. let componentConfigs = {
  1482. pieSlices: {
  1483. layerClass: 'pie-slices',
  1484. makeElements(data) {
  1485. return data.sliceStrings.map((s, i) =>{
  1486. let slice = makePath(s, 'pie-path', 'none', data.colors[i]);
  1487. slice.style.transition = 'transform .3s;';
  1488. return slice;
  1489. });
  1490. },
  1491. animateElements(newData) {
  1492. return this.store.map((slice, i) =>
  1493. animatePathStr(slice, newData.sliceStrings[i])
  1494. );
  1495. }
  1496. },
  1497. percentageBars: {
  1498. layerClass: 'percentage-bars',
  1499. makeElements(data) {
  1500. return data.xPositions.map((x, i) =>{
  1501. let y = 0;
  1502. let bar = percentageBar(x, y, data.widths[i],
  1503. this.constants.barHeight, this.constants.barDepth, data.colors[i]);
  1504. return bar;
  1505. });
  1506. },
  1507. animateElements(newData) {
  1508. if(newData) return [];
  1509. }
  1510. },
  1511. yAxis: {
  1512. layerClass: 'y axis',
  1513. makeElements(data) {
  1514. return data.positions.map((position, i) =>
  1515. yLine(position, data.labels[i], this.constants.width,
  1516. {mode: this.constants.mode, pos: this.constants.pos})
  1517. );
  1518. },
  1519. animateElements(newData) {
  1520. let newPos = newData.positions;
  1521. let newLabels = newData.labels;
  1522. let oldPos = this.oldData.positions;
  1523. let oldLabels = this.oldData.labels;
  1524. [oldPos, newPos] = equilizeNoOfElements(oldPos, newPos);
  1525. [oldLabels, newLabels] = equilizeNoOfElements(oldLabels, newLabels);
  1526. this.render({
  1527. positions: oldPos,
  1528. labels: newLabels
  1529. });
  1530. return this.store.map((line, i) => {
  1531. return translateHoriLine(
  1532. line, newPos[i], oldPos[i]
  1533. );
  1534. });
  1535. }
  1536. },
  1537. xAxis: {
  1538. layerClass: 'x axis',
  1539. makeElements(data) {
  1540. return data.positions.map((position, i) =>
  1541. xLine(position, data.calcLabels[i], this.constants.height,
  1542. {mode: this.constants.mode, pos: this.constants.pos})
  1543. );
  1544. },
  1545. animateElements(newData) {
  1546. let newPos = newData.positions;
  1547. let newLabels = newData.calcLabels;
  1548. let oldPos = this.oldData.positions;
  1549. let oldLabels = this.oldData.calcLabels;
  1550. [oldPos, newPos] = equilizeNoOfElements(oldPos, newPos);
  1551. [oldLabels, newLabels] = equilizeNoOfElements(oldLabels, newLabels);
  1552. this.render({
  1553. positions: oldPos,
  1554. calcLabels: newLabels
  1555. });
  1556. return this.store.map((line, i) => {
  1557. return translateVertLine(
  1558. line, newPos[i], oldPos[i]
  1559. );
  1560. });
  1561. }
  1562. },
  1563. yMarkers: {
  1564. layerClass: 'y-markers',
  1565. makeElements(data) {
  1566. return data.map(marker =>
  1567. yMarker(marker.position, marker.label, this.constants.width,
  1568. {pos:'right', mode: 'span', lineType: 'dashed'})
  1569. );
  1570. },
  1571. animateElements(newData) {
  1572. [this.oldData, newData] = equilizeNoOfElements(this.oldData, newData);
  1573. let newPos = newData.map(d => d.position);
  1574. let newLabels = newData.map(d => d.label);
  1575. let oldPos = this.oldData.map(d => d.position);
  1576. this.render(oldPos.map((pos, i) => {
  1577. return {
  1578. position: oldPos[i],
  1579. label: newLabels[i]
  1580. };
  1581. }));
  1582. return this.store.map((line, i) => {
  1583. return translateHoriLine(
  1584. line, newPos[i], oldPos[i]
  1585. );
  1586. });
  1587. }
  1588. },
  1589. yRegions: {
  1590. layerClass: 'y-regions',
  1591. makeElements(data) {
  1592. return data.map(region =>
  1593. yRegion(region.startPos, region.endPos, this.constants.width,
  1594. region.label)
  1595. );
  1596. },
  1597. animateElements(newData) {
  1598. [this.oldData, newData] = equilizeNoOfElements(this.oldData, newData);
  1599. let newPos = newData.map(d => d.endPos);
  1600. let newLabels = newData.map(d => d.label);
  1601. let newStarts = newData.map(d => d.startPos);
  1602. let oldPos = this.oldData.map(d => d.endPos);
  1603. let oldStarts = this.oldData.map(d => d.startPos);
  1604. this.render(oldPos.map((pos, i) => {
  1605. return {
  1606. startPos: oldStarts[i],
  1607. endPos: oldPos[i],
  1608. label: newLabels[i]
  1609. };
  1610. }));
  1611. let animateElements = [];
  1612. this.store.map((rectGroup, i) => {
  1613. animateElements = animateElements.concat(animateRegion(
  1614. rectGroup, newStarts[i], newPos[i], oldPos[i]
  1615. ));
  1616. });
  1617. return animateElements;
  1618. }
  1619. },
  1620. heatDomain: {
  1621. layerClass: function() { return 'heat-domain domain-' + this.constants.index; },
  1622. makeElements(data) {
  1623. let {index, colWidth, rowHeight, squareSize, xTranslate} = this.constants;
  1624. let monthNameHeight = -12;
  1625. let x = xTranslate, y = 0;
  1626. this.serializedSubDomains = [];
  1627. data.cols.map((week, weekNo) => {
  1628. if(weekNo === 1) {
  1629. this.labels.push(
  1630. makeText('domain-name', x, monthNameHeight, getMonthName(index, true),
  1631. {
  1632. fontSize: 11
  1633. }
  1634. )
  1635. );
  1636. }
  1637. week.map((day, i) => {
  1638. if(day.fill) {
  1639. let data = {
  1640. 'data-date': day.yyyyMmDd,
  1641. 'data-value': day.dataValue,
  1642. 'data-day': i
  1643. };
  1644. let square = heatSquare('day', x, y, squareSize, day.fill, data);
  1645. this.serializedSubDomains.push(square);
  1646. }
  1647. y += rowHeight;
  1648. });
  1649. y = 0;
  1650. x += colWidth;
  1651. });
  1652. return this.serializedSubDomains;
  1653. },
  1654. animateElements(newData) {
  1655. if(newData) return [];
  1656. }
  1657. },
  1658. barGraph: {
  1659. layerClass: function() { return 'dataset-units dataset-bars dataset-' + this.constants.index; },
  1660. makeElements(data) {
  1661. let c = this.constants;
  1662. this.unitType = 'bar';
  1663. this.units = data.yPositions.map((y, j) => {
  1664. return datasetBar(
  1665. data.xPositions[j],
  1666. y,
  1667. data.barWidth,
  1668. c.color,
  1669. data.labels[j],
  1670. j,
  1671. data.offsets[j],
  1672. {
  1673. zeroLine: data.zeroLine,
  1674. barsWidth: data.barsWidth,
  1675. minHeight: c.minHeight
  1676. }
  1677. );
  1678. });
  1679. return this.units;
  1680. },
  1681. animateElements(newData) {
  1682. let newXPos = newData.xPositions;
  1683. let newYPos = newData.yPositions;
  1684. let newOffsets = newData.offsets;
  1685. let newLabels = newData.labels;
  1686. let oldXPos = this.oldData.xPositions;
  1687. let oldYPos = this.oldData.yPositions;
  1688. let oldOffsets = this.oldData.offsets;
  1689. let oldLabels = this.oldData.labels;
  1690. [oldXPos, newXPos] = equilizeNoOfElements(oldXPos, newXPos);
  1691. [oldYPos, newYPos] = equilizeNoOfElements(oldYPos, newYPos);
  1692. [oldOffsets, newOffsets] = equilizeNoOfElements(oldOffsets, newOffsets);
  1693. [oldLabels, newLabels] = equilizeNoOfElements(oldLabels, newLabels);
  1694. this.render({
  1695. xPositions: oldXPos,
  1696. yPositions: oldYPos,
  1697. offsets: oldOffsets,
  1698. labels: newLabels,
  1699. zeroLine: this.oldData.zeroLine,
  1700. barsWidth: this.oldData.barsWidth,
  1701. barWidth: this.oldData.barWidth,
  1702. });
  1703. let animateElements = [];
  1704. this.store.map((bar, i) => {
  1705. animateElements = animateElements.concat(animateBar(
  1706. bar, newXPos[i], newYPos[i], newData.barWidth, newOffsets[i],
  1707. {zeroLine: newData.zeroLine}
  1708. ));
  1709. });
  1710. return animateElements;
  1711. }
  1712. },
  1713. lineGraph: {
  1714. layerClass: function() { return 'dataset-units dataset-line dataset-' + this.constants.index; },
  1715. makeElements(data) {
  1716. let c = this.constants;
  1717. this.unitType = 'dot';
  1718. this.paths = {};
  1719. if(!c.hideLine) {
  1720. this.paths = getPaths(
  1721. data.xPositions,
  1722. data.yPositions,
  1723. c.color,
  1724. {
  1725. heatline: c.heatline,
  1726. regionFill: c.regionFill
  1727. },
  1728. {
  1729. svgDefs: c.svgDefs,
  1730. zeroLine: data.zeroLine
  1731. }
  1732. );
  1733. }
  1734. this.units = [];
  1735. if(!c.hideDots) {
  1736. this.units = data.yPositions.map((y, j) => {
  1737. return datasetDot(
  1738. data.xPositions[j],
  1739. y,
  1740. data.radius,
  1741. c.color,
  1742. (c.valuesOverPoints ? data.values[j] : ''),
  1743. j
  1744. );
  1745. });
  1746. }
  1747. return Object.values(this.paths).concat(this.units);
  1748. },
  1749. animateElements(newData) {
  1750. let newXPos = newData.xPositions;
  1751. let newYPos = newData.yPositions;
  1752. let newValues = newData.values;
  1753. let oldXPos = this.oldData.xPositions;
  1754. let oldYPos = this.oldData.yPositions;
  1755. let oldValues = this.oldData.values;
  1756. [oldXPos, newXPos] = equilizeNoOfElements(oldXPos, newXPos);
  1757. [oldYPos, newYPos] = equilizeNoOfElements(oldYPos, newYPos);
  1758. [oldValues, newValues] = equilizeNoOfElements(oldValues, newValues);
  1759. this.render({
  1760. xPositions: oldXPos,
  1761. yPositions: oldYPos,
  1762. values: newValues,
  1763. zeroLine: this.oldData.zeroLine,
  1764. radius: this.oldData.radius,
  1765. });
  1766. let animateElements = [];
  1767. if(Object.keys(this.paths).length) {
  1768. animateElements = animateElements.concat(animatePath(
  1769. this.paths, newXPos, newYPos, newData.zeroLine));
  1770. }
  1771. if(this.units.length) {
  1772. this.units.map((dot, i) => {
  1773. animateElements = animateElements.concat(animateDot(
  1774. dot, newXPos[i], newYPos[i]));
  1775. });
  1776. }
  1777. return animateElements;
  1778. }
  1779. }
  1780. };
  1781. function getComponent(name, constants, getData) {
  1782. let keys = Object.keys(componentConfigs).filter(k => name.includes(k));
  1783. let config = componentConfigs[keys[0]];
  1784. Object.assign(config, {
  1785. constants: constants,
  1786. getData: getData
  1787. });
  1788. return new ChartComponent(config);
  1789. }
  1790. class PercentageChart extends AggregationChart {
  1791. constructor(parent, args) {
  1792. super(parent, args);
  1793. this.type = 'percentage';
  1794. this.barOptions = args.barOptions || {};
  1795. this.barOptions.height = this.barOptions.height
  1796. || PERCENTAGE_BAR_DEFAULT_HEIGHT;
  1797. this.barOptions.depth = this.barOptions.depth
  1798. || PERCENTAGE_BAR_DEFAULT_DEPTH;
  1799. this.setup();
  1800. }
  1801. setupComponents() {
  1802. let s = this.state;
  1803. let componentConfigs = [
  1804. [
  1805. 'percentageBars',
  1806. {
  1807. barHeight: this.barOptions.height,
  1808. barDepth: this.barOptions.depth,
  1809. },
  1810. function() {
  1811. return {
  1812. xPositions: s.xPositions,
  1813. widths: s.widths,
  1814. colors: this.colors
  1815. };
  1816. }.bind(this)
  1817. ]
  1818. ];
  1819. this.components = new Map(componentConfigs
  1820. .map(args => {
  1821. let component = getComponent(...args);
  1822. return [args[0], component];
  1823. }));
  1824. }
  1825. calc() {
  1826. super.calc();
  1827. let s = this.state;
  1828. s.xPositions = [];
  1829. s.widths = [];
  1830. let xPos = 0;
  1831. s.sliceTotals.map((value) => {
  1832. let width = this.width * value / s.grandTotal;
  1833. s.widths.push(width);
  1834. s.xPositions.push(xPos);
  1835. xPos += width;
  1836. });
  1837. }
  1838. makeDataByIndex() { }
  1839. bindTooltip() {
  1840. let s = this.state;
  1841. this.container.addEventListener('mousemove', (e) => {
  1842. let bars = this.components.get('percentageBars').store;
  1843. let bar = e.target;
  1844. if(bars.includes(bar)) {
  1845. let i = bars.indexOf(bar);
  1846. let gOff = getOffset(this.container), pOff = getOffset(bar);
  1847. let x = pOff.left - gOff.left + parseInt(bar.getAttribute('width'))/2;
  1848. let y = pOff.top - gOff.top;
  1849. let title = (this.formattedLabels && this.formattedLabels.length>0
  1850. ? this.formattedLabels[i] : this.state.labels[i]) + ': ';
  1851. let fraction = s.sliceTotals[i]/s.grandTotal;
  1852. this.tip.setValues(x, y, {name: title, value: (fraction*100).toFixed(1) + "%"});
  1853. this.tip.showTip();
  1854. }
  1855. });
  1856. }
  1857. }
  1858. class PieChart extends AggregationChart {
  1859. constructor(parent, args) {
  1860. super(parent, args);
  1861. this.type = 'pie';
  1862. this.initTimeout = 0;
  1863. this.init = 1;
  1864. this.setup();
  1865. }
  1866. configure(args) {
  1867. super.configure(args);
  1868. this.mouseMove = this.mouseMove.bind(this);
  1869. this.mouseLeave = this.mouseLeave.bind(this);
  1870. this.hoverRadio = args.hoverRadio || 0.1;
  1871. this.config.startAngle = args.startAngle || 0;
  1872. this.clockWise = args.clockWise || false;
  1873. }
  1874. calc() {
  1875. super.calc();
  1876. let s = this.state;
  1877. this.radius = (this.height > this.width ? this.center.x : this.center.y);
  1878. const { radius, clockWise } = this;
  1879. const prevSlicesProperties = s.slicesProperties || [];
  1880. s.sliceStrings = [];
  1881. s.slicesProperties = [];
  1882. let curAngle = 180 - this.config.startAngle;
  1883. s.sliceTotals.map((total, i) => {
  1884. const startAngle = curAngle;
  1885. const originDiffAngle = (total / s.grandTotal) * FULL_ANGLE;
  1886. const diffAngle = clockWise ? -originDiffAngle : originDiffAngle;
  1887. const endAngle = curAngle = curAngle + diffAngle;
  1888. const startPosition = getPositionByAngle(startAngle, radius);
  1889. const endPosition = getPositionByAngle(endAngle, radius);
  1890. const prevProperty = this.init && prevSlicesProperties[i];
  1891. let curStart,curEnd;
  1892. if(this.init) {
  1893. curStart = prevProperty ? prevProperty.startPosition : startPosition;
  1894. curEnd = prevProperty ? prevProperty.endPosition : startPosition;
  1895. } else {
  1896. curStart = startPosition;
  1897. curEnd = endPosition;
  1898. }
  1899. const curPath = makeArcPathStr(curStart, curEnd, this.center, this.radius, this.clockWise);
  1900. s.sliceStrings.push(curPath);
  1901. s.slicesProperties.push({
  1902. startPosition,
  1903. endPosition,
  1904. value: total,
  1905. total: s.grandTotal,
  1906. startAngle,
  1907. endAngle,
  1908. angle: diffAngle
  1909. });
  1910. });
  1911. this.init = 0;
  1912. }
  1913. setupComponents() {
  1914. let s = this.state;
  1915. let componentConfigs = [
  1916. [
  1917. 'pieSlices',
  1918. { },
  1919. function() {
  1920. return {
  1921. sliceStrings: s.sliceStrings,
  1922. colors: this.colors
  1923. };
  1924. }.bind(this)
  1925. ]
  1926. ];
  1927. this.components = new Map(componentConfigs
  1928. .map(args => {
  1929. let component = getComponent(...args);
  1930. return [args[0], component];
  1931. }));
  1932. }
  1933. calTranslateByAngle(property){
  1934. const{radius,hoverRadio} = this;
  1935. const position = getPositionByAngle(property.startAngle+(property.angle / 2),radius);
  1936. return `translate3d(${(position.x) * hoverRadio}px,${(position.y) * hoverRadio}px,0)`;
  1937. }
  1938. hoverSlice(path,i,flag,e){
  1939. if(!path) return;
  1940. const color = this.colors[i];
  1941. if(flag) {
  1942. transform(path, this.calTranslateByAngle(this.state.slicesProperties[i]));
  1943. path.style.fill = lightenDarkenColor(color, 50);
  1944. let g_off = getOffset(this.svg);
  1945. let x = e.pageX - g_off.left + 10;
  1946. let y = e.pageY - g_off.top - 10;
  1947. let title = (this.formatted_labels && this.formatted_labels.length > 0
  1948. ? this.formatted_labels[i] : this.state.labels[i]) + ': ';
  1949. let percent = (this.state.sliceTotals[i] * 100 / this.state.grandTotal).toFixed(1);
  1950. this.tip.setValues(x, y, {name: title, value: percent + "%"});
  1951. this.tip.showTip();
  1952. } else {
  1953. transform(path,'translate3d(0,0,0)');
  1954. this.tip.hideTip();
  1955. path.style.fill = color;
  1956. }
  1957. }
  1958. bindTooltip() {
  1959. this.container.addEventListener('mousemove', this.mouseMove);
  1960. this.container.addEventListener('mouseleave', this.mouseLeave);
  1961. }
  1962. mouseMove(e){
  1963. const target = e.target;
  1964. let slices = this.components.get('pieSlices').store;
  1965. let prevIndex = this.curActiveSliceIndex;
  1966. let prevAcitve = this.curActiveSlice;
  1967. if(slices.includes(target)) {
  1968. let i = slices.indexOf(target);
  1969. this.hoverSlice(prevAcitve, prevIndex,false);
  1970. this.curActiveSlice = target;
  1971. this.curActiveSliceIndex = i;
  1972. this.hoverSlice(target, i, true, e);
  1973. } else {
  1974. this.mouseLeave();
  1975. }
  1976. }
  1977. mouseLeave(){
  1978. this.hoverSlice(this.curActiveSlice,this.curActiveSliceIndex,false);
  1979. }
  1980. }
  1981. function normalize(x) {
  1982. // Calculates mantissa and exponent of a number
  1983. // Returns normalized number and exponent
  1984. // https://stackoverflow.com/q/9383593/6495043
  1985. if(x===0) {
  1986. return [0, 0];
  1987. }
  1988. if(isNaN(x)) {
  1989. return {mantissa: -6755399441055744, exponent: 972};
  1990. }
  1991. var sig = x > 0 ? 1 : -1;
  1992. if(!isFinite(x)) {
  1993. return {mantissa: sig * 4503599627370496, exponent: 972};
  1994. }
  1995. x = Math.abs(x);
  1996. var exp = Math.floor(Math.log10(x));
  1997. var man = x/Math.pow(10, exp);
  1998. return [sig * man, exp];
  1999. }
  2000. function getChartRangeIntervals(max, min=0) {
  2001. let upperBound = Math.ceil(max);
  2002. let lowerBound = Math.floor(min);
  2003. let range = upperBound - lowerBound;
  2004. let noOfParts = range;
  2005. let partSize = 1;
  2006. // To avoid too many partitions
  2007. if(range > 5) {
  2008. if(range % 2 !== 0) {
  2009. upperBound++;
  2010. // Recalc range
  2011. range = upperBound - lowerBound;
  2012. }
  2013. noOfParts = range/2;
  2014. partSize = 2;
  2015. }
  2016. // Special case: 1 and 2
  2017. if(range <= 2) {
  2018. noOfParts = 4;
  2019. partSize = range/noOfParts;
  2020. }
  2021. // Special case: 0
  2022. if(range === 0) {
  2023. noOfParts = 5;
  2024. partSize = 1;
  2025. }
  2026. let intervals = [];
  2027. for(var i = 0; i <= noOfParts; i++){
  2028. intervals.push(lowerBound + partSize * i);
  2029. }
  2030. return intervals;
  2031. }
  2032. function getChartIntervals(maxValue, minValue=0) {
  2033. let [normalMaxValue, exponent] = normalize(maxValue);
  2034. let normalMinValue = minValue ? minValue/Math.pow(10, exponent): 0;
  2035. // Allow only 7 significant digits
  2036. normalMaxValue = normalMaxValue.toFixed(6);
  2037. let intervals = getChartRangeIntervals(normalMaxValue, normalMinValue);
  2038. intervals = intervals.map(value => value * Math.pow(10, exponent));
  2039. return intervals;
  2040. }
  2041. function calcChartIntervals(values, withMinimum=false) {
  2042. //*** Where the magic happens ***
  2043. // Calculates best-fit y intervals from given values
  2044. // and returns the interval array
  2045. let maxValue = Math.max(...values);
  2046. let minValue = Math.min(...values);
  2047. // Exponent to be used for pretty print
  2048. let exponent = 0, intervals = []; // eslint-disable-line no-unused-vars
  2049. function getPositiveFirstIntervals(maxValue, absMinValue) {
  2050. let intervals = getChartIntervals(maxValue);
  2051. let intervalSize = intervals[1] - intervals[0];
  2052. // Then unshift the negative values
  2053. let value = 0;
  2054. for(var i = 1; value < absMinValue; i++) {
  2055. value += intervalSize;
  2056. intervals.unshift((-1) * value);
  2057. }
  2058. return intervals;
  2059. }
  2060. // CASE I: Both non-negative
  2061. if(maxValue >= 0 && minValue >= 0) {
  2062. exponent = normalize(maxValue)[1];
  2063. if(!withMinimum) {
  2064. intervals = getChartIntervals(maxValue);
  2065. } else {
  2066. intervals = getChartIntervals(maxValue, minValue);
  2067. }
  2068. }
  2069. // CASE II: Only minValue negative
  2070. else if(maxValue > 0 && minValue < 0) {
  2071. // `withMinimum` irrelevant in this case,
  2072. // We'll be handling both sides of zero separately
  2073. // (both starting from zero)
  2074. // Because ceil() and floor() behave differently
  2075. // in those two regions
  2076. let absMinValue = Math.abs(minValue);
  2077. if(maxValue >= absMinValue) {
  2078. exponent = normalize(maxValue)[1];
  2079. intervals = getPositiveFirstIntervals(maxValue, absMinValue);
  2080. } else {
  2081. // Mirror: maxValue => absMinValue, then change sign
  2082. exponent = normalize(absMinValue)[1];
  2083. let posIntervals = getPositiveFirstIntervals(absMinValue, maxValue);
  2084. intervals = posIntervals.map(d => d * (-1));
  2085. }
  2086. }
  2087. // CASE III: Both non-positive
  2088. else if(maxValue <= 0 && minValue <= 0) {
  2089. // Mirrored Case I:
  2090. // Work with positives, then reverse the sign and array
  2091. let pseudoMaxValue = Math.abs(minValue);
  2092. let pseudoMinValue = Math.abs(maxValue);
  2093. exponent = normalize(pseudoMaxValue)[1];
  2094. if(!withMinimum) {
  2095. intervals = getChartIntervals(pseudoMaxValue);
  2096. } else {
  2097. intervals = getChartIntervals(pseudoMaxValue, pseudoMinValue);
  2098. }
  2099. intervals = intervals.reverse().map(d => d * (-1));
  2100. }
  2101. return intervals;
  2102. }
  2103. function getZeroIndex(yPts) {
  2104. let zeroIndex;
  2105. let interval = getIntervalSize(yPts);
  2106. if(yPts.indexOf(0) >= 0) {
  2107. // the range has a given zero
  2108. // zero-line on the chart
  2109. zeroIndex = yPts.indexOf(0);
  2110. } else if(yPts[0] > 0) {
  2111. // Minimum value is positive
  2112. // zero-line is off the chart: below
  2113. let min = yPts[0];
  2114. zeroIndex = (-1) * min / interval;
  2115. } else {
  2116. // Maximum value is negative
  2117. // zero-line is off the chart: above
  2118. let max = yPts[yPts.length - 1];
  2119. zeroIndex = (-1) * max / interval + (yPts.length - 1);
  2120. }
  2121. return zeroIndex;
  2122. }
  2123. function getIntervalSize(orderedArray) {
  2124. return orderedArray[1] - orderedArray[0];
  2125. }
  2126. function getValueRange(orderedArray) {
  2127. return orderedArray[orderedArray.length-1] - orderedArray[0];
  2128. }
  2129. function scale(val, yAxis) {
  2130. return floatTwo(yAxis.zeroLine - val * yAxis.scaleMultiplier);
  2131. }
  2132. function getClosestInArray(goal, arr, index = false) {
  2133. let closest = arr.reduce(function(prev, curr) {
  2134. return (Math.abs(curr - goal) < Math.abs(prev - goal) ? curr : prev);
  2135. });
  2136. return index ? arr.indexOf(closest) : closest;
  2137. }
  2138. function calcDistribution(values, distributionSize) {
  2139. // Assume non-negative values,
  2140. // implying distribution minimum at zero
  2141. let dataMaxValue = Math.max(...values);
  2142. let distributionStep = 1 / (distributionSize - 1);
  2143. let distribution = [];
  2144. for(var i = 0; i < distributionSize; i++) {
  2145. let checkpoint = dataMaxValue * (distributionStep * i);
  2146. distribution.push(checkpoint);
  2147. }
  2148. return distribution;
  2149. }
  2150. function getMaxCheckpoint(value, distribution) {
  2151. return distribution.filter(d => d < value).length;
  2152. }
  2153. const COL_WIDTH = HEATMAP_SQUARE_SIZE + HEATMAP_GUTTER_SIZE;
  2154. const ROW_HEIGHT = COL_WIDTH;
  2155. // const DAY_INCR = 1;
  2156. class Heatmap extends BaseChart {
  2157. constructor(parent, options) {
  2158. super(parent, options);
  2159. this.type = 'heatmap';
  2160. this.discreteDomains = options.discreteDomains === 0 ? 0 : 1;
  2161. this.countLabel = options.countLabel || '';
  2162. let validStarts = ['Sunday', 'Monday'];
  2163. let startSubDomain = validStarts.includes(options.startSubDomain)
  2164. ? options.startSubDomain : 'Sunday';
  2165. this.startSubDomainIndex = validStarts.indexOf(startSubDomain);
  2166. this.setup();
  2167. }
  2168. setMargins() {
  2169. super.setMargins();
  2170. this.leftMargin = HEATMAP_LEFT_MARGIN;
  2171. this.topMargin = HEATMAP_TOP_MARGIN;
  2172. }
  2173. updateWidth() {
  2174. this.baseWidth = (this.state.noOfWeeks + 99) * COL_WIDTH;
  2175. if(this.discreteDomains) {
  2176. this.baseWidth += (COL_WIDTH * NO_OF_YEAR_MONTHS);
  2177. }
  2178. }
  2179. prepareData(data=this.data) {
  2180. if(data.start && data.end && data.start > data.end) {
  2181. throw new Error('Start date cannot be greater than end date.');
  2182. }
  2183. if(!data.start) {
  2184. data.start = new Date();
  2185. data.start.setFullYear( data.start.getFullYear() - 1 );
  2186. }
  2187. if(!data.end) { data.end = new Date(); }
  2188. data.dataPoints = data.dataPoints || {};
  2189. if(parseInt(Object.keys(data.dataPoints)[0]) > 100000) {
  2190. let points = {};
  2191. Object.keys(data.dataPoints).forEach(timestampSec$$1 => {
  2192. let date = new Date(timestampSec$$1 * NO_OF_MILLIS);
  2193. points[getYyyyMmDd(date)] = data.dataPoints[timestampSec$$1];
  2194. });
  2195. data.dataPoints = points;
  2196. }
  2197. return data;
  2198. }
  2199. calc() {
  2200. let s = this.state;
  2201. s.start = clone(this.data.start);
  2202. s.end = clone(this.data.end);
  2203. s.firstWeekStart = clone(s.start);
  2204. s.noOfWeeks = getWeeksBetween(s.start, s.end);
  2205. s.distribution = calcDistribution(
  2206. Object.values(this.data.dataPoints), HEATMAP_DISTRIBUTION_SIZE);
  2207. s.domainConfigs = this.getDomains();
  2208. }
  2209. setupComponents() {
  2210. let s = this.state;
  2211. let lessCol = this.discreteDomains ? 0 : 1;
  2212. let componentConfigs = s.domainConfigs.map((config, i) => [
  2213. 'heatDomain',
  2214. {
  2215. index: config.index,
  2216. colWidth: COL_WIDTH,
  2217. rowHeight: ROW_HEIGHT,
  2218. squareSize: HEATMAP_SQUARE_SIZE,
  2219. xTranslate: s.domainConfigs
  2220. .filter((config, j) => j < i)
  2221. .map(config => config.cols.length - lessCol)
  2222. .reduce((a, b) => a + b, 0)
  2223. * COL_WIDTH
  2224. },
  2225. function() {
  2226. return s.domainConfigs[i];
  2227. }.bind(this)
  2228. ]);
  2229. this.components = new Map(componentConfigs
  2230. .map((args, i) => {
  2231. let component = getComponent(...args);
  2232. return [args[0] + '-' + i, component];
  2233. }));
  2234. let y = 0;
  2235. DAY_NAMES_SHORT.forEach((dayName, i) => {
  2236. if([1, 3, 5].includes(i)) {
  2237. let dayText = makeText('subdomain-name', -COL_WIDTH/2, y, dayName,
  2238. {
  2239. fontSize: HEATMAP_SQUARE_SIZE,
  2240. dy: 8,
  2241. textAnchor: 'end'
  2242. }
  2243. );
  2244. this.drawArea.appendChild(dayText);
  2245. }
  2246. y += ROW_HEIGHT;
  2247. });
  2248. }
  2249. update(data) {
  2250. if(!data) {
  2251. console.error('No data to update.');
  2252. }
  2253. this.data = this.prepareData(data);
  2254. this.draw();
  2255. this.bindTooltip();
  2256. }
  2257. bindTooltip() {
  2258. this.container.addEventListener('mousemove', (e) => {
  2259. this.components.forEach(comp => {
  2260. let daySquares = comp.store;
  2261. let daySquare = e.target;
  2262. if(daySquares.includes(daySquare)) {
  2263. let count = daySquare.getAttribute('data-value');
  2264. let dateParts = daySquare.getAttribute('data-date').split('-');
  2265. let month = getMonthName(parseInt(dateParts[1])-1, true);
  2266. let gOff = this.container.getBoundingClientRect(), pOff = daySquare.getBoundingClientRect();
  2267. let width = parseInt(e.target.getAttribute('width'));
  2268. let x = pOff.left - gOff.left + width/2;
  2269. let y = pOff.top - gOff.top;
  2270. let value = count + ' ' + this.countLabel;
  2271. let name = ' on ' + month + ' ' + dateParts[0] + ', ' + dateParts[2];
  2272. this.tip.setValues(x, y, {name: name, value: value, valueFirst: 1}, []);
  2273. this.tip.showTip();
  2274. }
  2275. });
  2276. });
  2277. }
  2278. renderLegend() {
  2279. this.legendArea.textContent = '';
  2280. let x = 0;
  2281. let y = ROW_HEIGHT;
  2282. let lessText = makeText('subdomain-name', x, y, 'Less',
  2283. {
  2284. fontSize: HEATMAP_SQUARE_SIZE + 1,
  2285. dy: 9
  2286. }
  2287. );
  2288. x = (COL_WIDTH * 2) + COL_WIDTH/2;
  2289. this.legendArea.appendChild(lessText);
  2290. this.colors.slice(0, HEATMAP_DISTRIBUTION_SIZE).map((color, i) => {
  2291. const square = heatSquare('heatmap-legend-unit', x + (COL_WIDTH + 3) * i,
  2292. y, HEATMAP_SQUARE_SIZE, color);
  2293. this.legendArea.appendChild(square);
  2294. });
  2295. let moreTextX = x + HEATMAP_DISTRIBUTION_SIZE * (COL_WIDTH + 3) + COL_WIDTH/4;
  2296. let moreText = makeText('subdomain-name', moreTextX, y, 'More',
  2297. {
  2298. fontSize: HEATMAP_SQUARE_SIZE + 1,
  2299. dy: 9
  2300. }
  2301. );
  2302. this.legendArea.appendChild(moreText);
  2303. }
  2304. getDomains() {
  2305. let s = this.state;
  2306. const [startMonth, startYear] = [s.start.getMonth(), s.start.getFullYear()];
  2307. const [endMonth, endYear] = [s.end.getMonth(), s.end.getFullYear()];
  2308. const noOfMonths = (endMonth - startMonth + 1) + (endYear - startYear) * 12;
  2309. let domainConfigs = [];
  2310. let startOfMonth = clone(s.start);
  2311. for(var i = 0; i < noOfMonths; i++) {
  2312. let endDate = s.end;
  2313. if(!areInSameMonth(startOfMonth, s.end)) {
  2314. let [month, year] = [startOfMonth.getMonth(), startOfMonth.getFullYear()];
  2315. endDate = getLastDateInMonth(month, year);
  2316. }
  2317. domainConfigs.push(this.getDomainConfig(startOfMonth, endDate));
  2318. addDays(endDate, 1);
  2319. startOfMonth = endDate;
  2320. }
  2321. return domainConfigs;
  2322. }
  2323. getDomainConfig(startDate, endDate='') {
  2324. let [month, year] = [startDate.getMonth(), startDate.getFullYear()];
  2325. let startOfWeek = setDayToSunday(startDate); // TODO: Monday as well
  2326. endDate = clone(endDate) || getLastDateInMonth(month, year);
  2327. let domainConfig = {
  2328. index: month,
  2329. cols: []
  2330. };
  2331. addDays(endDate, 1);
  2332. let noOfMonthWeeks = getWeeksBetween(startOfWeek, endDate);
  2333. let cols = [], col;
  2334. for(var i = 0; i < noOfMonthWeeks; i++) {
  2335. col = this.getCol(startOfWeek, month);
  2336. cols.push(col);
  2337. startOfWeek = new Date(col[NO_OF_DAYS_IN_WEEK - 1].yyyyMmDd);
  2338. addDays(startOfWeek, 1);
  2339. }
  2340. if(col[NO_OF_DAYS_IN_WEEK - 1].dataValue) {
  2341. addDays(startOfWeek, 1);
  2342. cols.push(this.getCol(startOfWeek, month, true));
  2343. }
  2344. domainConfig.cols = cols;
  2345. return domainConfig;
  2346. }
  2347. getCol(startDate, month, empty = false) {
  2348. let s = this.state;
  2349. // startDate is the start of week
  2350. let currentDate = clone(startDate);
  2351. let col = [];
  2352. for(var i = 0; i < NO_OF_DAYS_IN_WEEK; i++, addDays(currentDate, 1)) {
  2353. let config = {};
  2354. // Non-generic adjustment for entire heatmap, needs state
  2355. let currentDateWithinData = currentDate >= s.start && currentDate <= s.end;
  2356. if(empty || currentDate.getMonth() !== month || !currentDateWithinData) {
  2357. config.yyyyMmDd = getYyyyMmDd(currentDate);
  2358. } else {
  2359. config = this.getSubDomainConfig(currentDate);
  2360. }
  2361. col.push(config);
  2362. }
  2363. return col;
  2364. }
  2365. getSubDomainConfig(date) {
  2366. let yyyyMmDd = getYyyyMmDd(date);
  2367. let dataValue = this.data.dataPoints[yyyyMmDd];
  2368. let config = {
  2369. yyyyMmDd: yyyyMmDd,
  2370. dataValue: dataValue || 0,
  2371. fill: this.colors[getMaxCheckpoint(dataValue, this.state.distribution)]
  2372. };
  2373. return config;
  2374. }
  2375. }
  2376. function dataPrep(data, type) {
  2377. data.labels = data.labels || [];
  2378. let datasetLength = data.labels.length;
  2379. // Datasets
  2380. let datasets = data.datasets;
  2381. let zeroArray = new Array(datasetLength).fill(0);
  2382. if(!datasets) {
  2383. // default
  2384. datasets = [{
  2385. values: zeroArray
  2386. }];
  2387. }
  2388. datasets.map(d=> {
  2389. // Set values
  2390. if(!d.values) {
  2391. d.values = zeroArray;
  2392. } else {
  2393. // Check for non values
  2394. let vals = d.values;
  2395. vals = vals.map(val => (!isNaN(val) ? val : 0));
  2396. // Trim or extend
  2397. if(vals.length > datasetLength) {
  2398. vals = vals.slice(0, datasetLength);
  2399. } else {
  2400. vals = fillArray(vals, datasetLength - vals.length, 0);
  2401. }
  2402. }
  2403. // Set labels
  2404. //
  2405. // Set type
  2406. if(!d.chartType ) {
  2407. if(!AXIS_DATASET_CHART_TYPES.includes(type)) type === DEFAULT_AXIS_CHART_TYPE;
  2408. d.chartType = type;
  2409. }
  2410. });
  2411. // Markers
  2412. // Regions
  2413. // data.yRegions = data.yRegions || [];
  2414. if(data.yRegions) {
  2415. data.yRegions.map(d => {
  2416. if(d.end < d.start) {
  2417. [d.start, d.end] = [d.end, d.start];
  2418. }
  2419. });
  2420. }
  2421. return data;
  2422. }
  2423. function zeroDataPrep(realData) {
  2424. let datasetLength = realData.labels.length;
  2425. let zeroArray = new Array(datasetLength).fill(0);
  2426. let zeroData = {
  2427. labels: realData.labels.slice(0, -1),
  2428. datasets: realData.datasets.map(d => {
  2429. return {
  2430. name: '',
  2431. values: zeroArray.slice(0, -1),
  2432. chartType: d.chartType
  2433. };
  2434. }),
  2435. };
  2436. if(realData.yMarkers) {
  2437. zeroData.yMarkers = [
  2438. {
  2439. value: 0,
  2440. label: ''
  2441. }
  2442. ];
  2443. }
  2444. if(realData.yRegions) {
  2445. zeroData.yRegions = [
  2446. {
  2447. start: 0,
  2448. end: 0,
  2449. label: ''
  2450. }
  2451. ];
  2452. }
  2453. return zeroData;
  2454. }
  2455. function getShortenedLabels(chartWidth, labels=[], isSeries=true) {
  2456. let allowedSpace = chartWidth / labels.length;
  2457. let allowedLetters = allowedSpace / DEFAULT_CHAR_WIDTH;
  2458. let calcLabels = labels.map((label, i) => {
  2459. label += "";
  2460. if(label.length > allowedLetters) {
  2461. if(!isSeries) {
  2462. if(allowedLetters-3 > 0) {
  2463. label = label.slice(0, allowedLetters-3) + " ...";
  2464. } else {
  2465. label = label.slice(0, allowedLetters) + '..';
  2466. }
  2467. } else {
  2468. let multiple = Math.ceil(label.length/allowedLetters);
  2469. if(i % multiple !== 0) {
  2470. label = "";
  2471. }
  2472. }
  2473. }
  2474. return label;
  2475. });
  2476. return calcLabels;
  2477. }
  2478. class AxisChart extends BaseChart {
  2479. constructor(parent, args) {
  2480. super(parent, args);
  2481. this.barOptions = args.barOptions || {};
  2482. this.lineOptions = args.lineOptions || {};
  2483. this.type = args.type || 'line';
  2484. this.init = 1;
  2485. this.setup();
  2486. }
  2487. configure(args) {
  2488. super.configure(args);
  2489. args.axisOptions = args.axisOptions || {};
  2490. args.tooltipOptions = args.tooltipOptions || {};
  2491. this.config.xAxisMode = args.axisOptions.xAxisMode || 'span';
  2492. this.config.yAxisMode = args.axisOptions.yAxisMode || 'span';
  2493. this.config.xIsSeries = args.axisOptions.xIsSeries || 0;
  2494. this.config.formatTooltipX = args.tooltipOptions.formatTooltipX;
  2495. this.config.formatTooltipY = args.tooltipOptions.formatTooltipY;
  2496. this.config.valuesOverPoints = args.valuesOverPoints;
  2497. }
  2498. setMargins() {
  2499. super.setMargins();
  2500. this.leftMargin = Y_AXIS_LEFT_MARGIN;
  2501. this.rightMargin = Y_AXIS_RIGHT_MARGIN;
  2502. }
  2503. prepareData(data=this.data) {
  2504. return dataPrep(data, this.type);
  2505. }
  2506. prepareFirstData(data=this.data) {
  2507. return zeroDataPrep(data);
  2508. }
  2509. calc(onlyWidthChange = false) {
  2510. this.calcXPositions();
  2511. if(onlyWidthChange) return;
  2512. this.calcYAxisParameters(this.getAllYValues(), this.type === 'line');
  2513. this.makeDataByIndex();
  2514. }
  2515. calcXPositions() {
  2516. let s = this.state;
  2517. let labels = this.data.labels;
  2518. s.datasetLength = labels.length;
  2519. s.unitWidth = this.width/(s.datasetLength);
  2520. // Default, as per bar, and mixed. Only line will be a special case
  2521. s.xOffset = s.unitWidth/2;
  2522. // // For a pure Line Chart
  2523. // s.unitWidth = this.width/(s.datasetLength - 1);
  2524. // s.xOffset = 0;
  2525. s.xAxis = {
  2526. labels: labels,
  2527. positions: labels.map((d, i) =>
  2528. floatTwo(s.xOffset + i * s.unitWidth)
  2529. )
  2530. };
  2531. }
  2532. calcYAxisParameters(dataValues, withMinimum = 'false') {
  2533. const yPts = calcChartIntervals(dataValues, withMinimum);
  2534. const scaleMultiplier = this.height / getValueRange(yPts);
  2535. const intervalHeight = getIntervalSize(yPts) * scaleMultiplier;
  2536. const zeroLine = this.height - (getZeroIndex(yPts) * intervalHeight);
  2537. this.state.yAxis = {
  2538. labels: yPts,
  2539. positions: yPts.map(d => zeroLine - d * scaleMultiplier),
  2540. scaleMultiplier: scaleMultiplier,
  2541. zeroLine: zeroLine,
  2542. };
  2543. // Dependent if above changes
  2544. this.calcDatasetPoints();
  2545. this.calcYExtremes();
  2546. this.calcYRegions();
  2547. }
  2548. calcDatasetPoints() {
  2549. let s = this.state;
  2550. let scaleAll = values => values.map(val => scale(val, s.yAxis));
  2551. s.datasets = this.data.datasets.map((d, i) => {
  2552. let values = d.values;
  2553. let cumulativeYs = d.cumulativeYs || [];
  2554. return {
  2555. name: d.name,
  2556. index: i,
  2557. chartType: d.chartType,
  2558. values: values,
  2559. yPositions: scaleAll(values),
  2560. cumulativeYs: cumulativeYs,
  2561. cumulativeYPos: scaleAll(cumulativeYs),
  2562. };
  2563. });
  2564. }
  2565. calcYExtremes() {
  2566. let s = this.state;
  2567. if(this.barOptions.stacked) {
  2568. s.yExtremes = s.datasets[s.datasets.length - 1].cumulativeYPos;
  2569. return;
  2570. }
  2571. s.yExtremes = new Array(s.datasetLength).fill(9999);
  2572. s.datasets.map(d => {
  2573. d.yPositions.map((pos, j) => {
  2574. if(pos < s.yExtremes[j]) {
  2575. s.yExtremes[j] = pos;
  2576. }
  2577. });
  2578. });
  2579. }
  2580. calcYRegions() {
  2581. let s = this.state;
  2582. if(this.data.yMarkers) {
  2583. this.state.yMarkers = this.data.yMarkers.map(d => {
  2584. d.position = scale(d.value, s.yAxis);
  2585. // if(!d.label.includes(':')) {
  2586. // d.label += ': ' + d.value;
  2587. // }
  2588. return d;
  2589. });
  2590. }
  2591. if(this.data.yRegions) {
  2592. this.state.yRegions = this.data.yRegions.map(d => {
  2593. d.startPos = scale(d.start, s.yAxis);
  2594. d.endPos = scale(d.end, s.yAxis);
  2595. return d;
  2596. });
  2597. }
  2598. }
  2599. getAllYValues() {
  2600. let key = 'values';
  2601. if(this.barOptions.stacked) {
  2602. key = 'cumulativeYs';
  2603. let cumulative = new Array(this.state.datasetLength).fill(0);
  2604. this.data.datasets.map((d, i) => {
  2605. let values = this.data.datasets[i].values;
  2606. d[key] = cumulative = cumulative.map((c, i) => c + values[i]);
  2607. });
  2608. }
  2609. let allValueLists = this.data.datasets.map(d => d[key]);
  2610. if(this.data.yMarkers) {
  2611. allValueLists.push(this.data.yMarkers.map(d => d.value));
  2612. }
  2613. if(this.data.yRegions) {
  2614. this.data.yRegions.map(d => {
  2615. allValueLists.push([d.end, d.start]);
  2616. });
  2617. }
  2618. return [].concat(...allValueLists);
  2619. }
  2620. setupComponents() {
  2621. let componentConfigs = [
  2622. [
  2623. 'yAxis',
  2624. {
  2625. mode: this.config.yAxisMode,
  2626. width: this.width,
  2627. // pos: 'right'
  2628. },
  2629. function() {
  2630. return this.state.yAxis;
  2631. }.bind(this)
  2632. ],
  2633. [
  2634. 'xAxis',
  2635. {
  2636. mode: this.config.xAxisMode,
  2637. height: this.height,
  2638. // pos: 'right'
  2639. },
  2640. function() {
  2641. let s = this.state;
  2642. s.xAxis.calcLabels = getShortenedLabels(this.width,
  2643. s.xAxis.labels, this.config.xIsSeries);
  2644. return s.xAxis;
  2645. }.bind(this)
  2646. ],
  2647. [
  2648. 'yRegions',
  2649. {
  2650. width: this.width,
  2651. pos: 'right'
  2652. },
  2653. function() {
  2654. return this.state.yRegions;
  2655. }.bind(this)
  2656. ],
  2657. ];
  2658. let barDatasets = this.state.datasets.filter(d => d.chartType === 'bar');
  2659. let lineDatasets = this.state.datasets.filter(d => d.chartType === 'line');
  2660. let barsConfigs = barDatasets.map(d => {
  2661. let index = d.index;
  2662. return [
  2663. 'barGraph' + '-' + d.index,
  2664. {
  2665. index: index,
  2666. color: this.colors[index],
  2667. stacked: this.barOptions.stacked,
  2668. // same for all datasets
  2669. valuesOverPoints: this.config.valuesOverPoints,
  2670. minHeight: this.height * MIN_BAR_PERCENT_HEIGHT,
  2671. },
  2672. function() {
  2673. let s = this.state;
  2674. let d = s.datasets[index];
  2675. let stacked = this.barOptions.stacked;
  2676. let spaceRatio = this.barOptions.spaceRatio || BAR_CHART_SPACE_RATIO;
  2677. let barsWidth = s.unitWidth * (1 - spaceRatio);
  2678. let barWidth = barsWidth/(stacked ? 1 : barDatasets.length);
  2679. let xPositions = s.xAxis.positions.map(x => x - barsWidth/2);
  2680. if(!stacked) {
  2681. xPositions = xPositions.map(p => p + barWidth * index);
  2682. }
  2683. let labels = new Array(s.datasetLength).fill('');
  2684. if(this.config.valuesOverPoints) {
  2685. if(stacked && d.index === s.datasets.length - 1) {
  2686. labels = d.cumulativeYs;
  2687. } else {
  2688. labels = d.values;
  2689. }
  2690. }
  2691. let offsets = new Array(s.datasetLength).fill(0);
  2692. if(stacked) {
  2693. offsets = d.yPositions.map((y, j) => y - d.cumulativeYPos[j]);
  2694. }
  2695. return {
  2696. xPositions: xPositions,
  2697. yPositions: d.yPositions,
  2698. offsets: offsets,
  2699. // values: d.values,
  2700. labels: labels,
  2701. zeroLine: s.yAxis.zeroLine,
  2702. barsWidth: barsWidth,
  2703. barWidth: barWidth,
  2704. };
  2705. }.bind(this)
  2706. ];
  2707. });
  2708. let lineConfigs = lineDatasets.map(d => {
  2709. let index = d.index;
  2710. return [
  2711. 'lineGraph' + '-' + d.index,
  2712. {
  2713. index: index,
  2714. color: this.colors[index],
  2715. svgDefs: this.svgDefs,
  2716. heatline: this.lineOptions.heatline,
  2717. regionFill: this.lineOptions.regionFill,
  2718. hideDots: this.lineOptions.hideDots,
  2719. hideLine: this.lineOptions.hideLine,
  2720. // same for all datasets
  2721. valuesOverPoints: this.config.valuesOverPoints,
  2722. },
  2723. function() {
  2724. let s = this.state;
  2725. let d = s.datasets[index];
  2726. return {
  2727. xPositions: s.xAxis.positions,
  2728. yPositions: d.yPositions,
  2729. values: d.values,
  2730. zeroLine: s.yAxis.zeroLine,
  2731. radius: this.lineOptions.dotSize || LINE_CHART_DOT_SIZE,
  2732. };
  2733. }.bind(this)
  2734. ];
  2735. });
  2736. let markerConfigs = [
  2737. [
  2738. 'yMarkers',
  2739. {
  2740. width: this.width,
  2741. pos: 'right'
  2742. },
  2743. function() {
  2744. return this.state.yMarkers;
  2745. }.bind(this)
  2746. ]
  2747. ];
  2748. componentConfigs = componentConfigs.concat(barsConfigs, lineConfigs, markerConfigs);
  2749. let optionals = ['yMarkers', 'yRegions'];
  2750. this.dataUnitComponents = [];
  2751. this.components = new Map(componentConfigs
  2752. .filter(args => !optionals.includes(args[0]) || this.state[args[0]])
  2753. .map(args => {
  2754. let component = getComponent(...args);
  2755. if(args[0].includes('lineGraph') || args[0].includes('barGraph')) {
  2756. this.dataUnitComponents.push(component);
  2757. }
  2758. return [args[0], component];
  2759. }));
  2760. }
  2761. makeDataByIndex() {
  2762. this.dataByIndex = {};
  2763. let s = this.state;
  2764. // let formatY = this.config.formatTooltipY;
  2765. let formatX = this.config.formatTooltipX;
  2766. let titles = s.xAxis.labels;
  2767. if(formatX && formatX(titles[0])) {
  2768. titles = titles.map(d=>formatX(d));
  2769. }
  2770. // formatY = formatY && formatY(s.yAxis.labels[0]) ? formatY : 0;
  2771. // yVal = formatY ? formatY(set.values[i]) : set.values[i]
  2772. }
  2773. bindTooltip() {
  2774. // NOTE: could be in tooltip itself, as it is a given functionality for its parent
  2775. this.container.addEventListener('mousemove', (e) => {
  2776. let o = getOffset(this.container);
  2777. let relX = e.pageX - o.left - this.leftMargin;
  2778. let relY = e.pageY - o.top - this.topMargin;
  2779. if(relY < this.height + this.topMargin * 2) {
  2780. this.mapTooltipXPosition(relX);
  2781. } else {
  2782. this.tip.hideTip();
  2783. }
  2784. });
  2785. }
  2786. mapTooltipXPosition(relX) {
  2787. let s = this.state;
  2788. if(!s.yExtremes) return;
  2789. let index = getClosestInArray(relX, s.xAxis.positions, true);
  2790. this.tip.setValues(
  2791. s.xAxis.positions[index] + this.tip.offset.x,
  2792. s.yExtremes[index] + this.tip.offset.y,
  2793. {name: s.xAxis.labels[index], value: ''},
  2794. this.data.datasets.map((set, i) => {
  2795. return {
  2796. title: set.name,
  2797. value: set.values[index],
  2798. color: this.colors[i],
  2799. };
  2800. }),
  2801. index
  2802. );
  2803. this.tip.showTip();
  2804. }
  2805. renderLegend() {
  2806. let s = this.data;
  2807. this.legendArea.textContent = '';
  2808. if(s.datasets.length > 1) {
  2809. s.datasets.map((d, i) => {
  2810. let barWidth = AXIS_LEGEND_BAR_SIZE;
  2811. // let rightEndPoint = this.baseWidth - this.leftMargin - this.rightMargin;
  2812. // let multiplier = s.datasets.length - i;
  2813. let rect = legendBar(
  2814. // rightEndPoint - multiplier * barWidth, // To right align
  2815. barWidth * i,
  2816. '0',
  2817. barWidth,
  2818. this.colors[i],
  2819. d.name);
  2820. this.legendArea.appendChild(rect);
  2821. });
  2822. }
  2823. }
  2824. // Overlay
  2825. makeOverlay() {
  2826. if(this.init) {
  2827. this.init = 0;
  2828. return;
  2829. }
  2830. if(this.overlayGuides) {
  2831. this.overlayGuides.forEach(g => {
  2832. let o = g.overlay;
  2833. o.parentNode.removeChild(o);
  2834. });
  2835. }
  2836. this.overlayGuides = this.dataUnitComponents.map(c => {
  2837. return {
  2838. type: c.unitType,
  2839. overlay: undefined,
  2840. units: c.units,
  2841. };
  2842. });
  2843. if(this.state.currentIndex === undefined) {
  2844. this.state.currentIndex = this.state.datasetLength - 1;
  2845. }
  2846. // Render overlays
  2847. this.overlayGuides.map(d => {
  2848. let currentUnit = d.units[this.state.currentIndex];
  2849. d.overlay = makeOverlay[d.type](currentUnit);
  2850. this.drawArea.appendChild(d.overlay);
  2851. });
  2852. }
  2853. updateOverlayGuides() {
  2854. if(this.overlayGuides) {
  2855. this.overlayGuides.forEach(g => {
  2856. let o = g.overlay;
  2857. o.parentNode.removeChild(o);
  2858. });
  2859. }
  2860. }
  2861. bindOverlay() {
  2862. this.parent.addEventListener('data-select', () => {
  2863. this.updateOverlay();
  2864. });
  2865. }
  2866. bindUnits() {
  2867. this.dataUnitComponents.map(c => {
  2868. c.units.map(unit => {
  2869. unit.addEventListener('click', () => {
  2870. let index = unit.getAttribute('data-point-index');
  2871. this.setCurrentDataPoint(index);
  2872. });
  2873. });
  2874. });
  2875. // Note: Doesn't work as tooltip is absolutely positioned
  2876. this.tip.container.addEventListener('click', () => {
  2877. let index = this.tip.container.getAttribute('data-point-index');
  2878. this.setCurrentDataPoint(index);
  2879. });
  2880. }
  2881. updateOverlay() {
  2882. this.overlayGuides.map(d => {
  2883. let currentUnit = d.units[this.state.currentIndex];
  2884. updateOverlay[d.type](currentUnit, d.overlay);
  2885. });
  2886. }
  2887. onLeftArrow() {
  2888. this.setCurrentDataPoint(this.state.currentIndex - 1);
  2889. }
  2890. onRightArrow() {
  2891. this.setCurrentDataPoint(this.state.currentIndex + 1);
  2892. }
  2893. getDataPoint(index=this.state.currentIndex) {
  2894. let s = this.state;
  2895. let data_point = {
  2896. index: index,
  2897. label: s.xAxis.labels[index],
  2898. values: s.datasets.map(d => d.values[index])
  2899. };
  2900. return data_point;
  2901. }
  2902. setCurrentDataPoint(index) {
  2903. let s = this.state;
  2904. index = parseInt(index);
  2905. if(index < 0) index = 0;
  2906. if(index >= s.xAxis.labels.length) index = s.xAxis.labels.length - 1;
  2907. if(index === s.currentIndex) return;
  2908. s.currentIndex = index;
  2909. fire(this.parent, "data-select", this.getDataPoint());
  2910. }
  2911. // API
  2912. addDataPoint(label, datasetValues, index=this.state.datasetLength) {
  2913. super.addDataPoint(label, datasetValues, index);
  2914. this.data.labels.splice(index, 0, label);
  2915. this.data.datasets.map((d, i) => {
  2916. d.values.splice(index, 0, datasetValues[i]);
  2917. });
  2918. this.update(this.data);
  2919. }
  2920. removeDataPoint(index = this.state.datasetLength-1) {
  2921. if (this.data.labels.length <= 1) {
  2922. return;
  2923. }
  2924. super.removeDataPoint(index);
  2925. this.data.labels.splice(index, 1);
  2926. this.data.datasets.map(d => {
  2927. d.values.splice(index, 1);
  2928. });
  2929. this.update(this.data);
  2930. }
  2931. updateDataset(datasetValues, index=0) {
  2932. this.data.datasets[index].values = datasetValues;
  2933. this.update(this.data);
  2934. }
  2935. // addDataset(dataset, index) {}
  2936. // removeDataset(index = 0) {}
  2937. updateDatasets(datasets) {
  2938. this.data.datasets.map((d, i) => {
  2939. if(datasets[i]) {
  2940. d.values = datasets[i];
  2941. }
  2942. });
  2943. this.update(this.data);
  2944. }
  2945. // updateDataPoint(dataPoint, index = 0) {}
  2946. // addDataPoint(dataPoint, index = 0) {}
  2947. // removeDataPoint(index = 0) {}
  2948. }
  2949. const chartTypes = {
  2950. // multiaxis: MultiAxisChart,
  2951. percentage: PercentageChart,
  2952. heatmap: Heatmap,
  2953. pie: PieChart
  2954. };
  2955. function getChartByType(chartType = 'line', parent, options) {
  2956. if(chartType === 'line') {
  2957. options.type = 'line';
  2958. return new AxisChart(parent, options);
  2959. } else if (chartType === 'bar') {
  2960. options.type = 'bar';
  2961. return new AxisChart(parent, options);
  2962. } else if (chartType === 'axis-mixed') {
  2963. options.type = 'line';
  2964. return new AxisChart(parent, options);
  2965. }
  2966. if (!chartTypes[chartType]) {
  2967. console.error("Undefined chart type: " + chartType);
  2968. return;
  2969. }
  2970. return new chartTypes[chartType](parent, options);
  2971. }
  2972. class Chart {
  2973. constructor(parent, options) {
  2974. return getChartByType(options.type, parent, options);
  2975. }
  2976. }
  2977. export { Chart, PercentageChart, PieChart, Heatmap, AxisChart };