You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

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