No puede seleccionar más de 25 temas Los temas deben comenzar con una letra o número, pueden incluir guiones ('-') y pueden tener hasta 35 caracteres de largo.
 
 
 

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