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

3675 lignes
86 KiB

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