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.
 
 
 

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