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.
 
 
 

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