Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.
 
 
 

3883 řádky
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=0) {
  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){
  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 0 ${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(count > divisor) {
  1422. count = 0;
  1423. y += 20;
  1424. }
  1425. let x = barWidth * count + 5;
  1426. let dot = legendDot(
  1427. x,
  1428. y,
  1429. 5,
  1430. this.colors[i],
  1431. `${s.labels[i]}: ${d}`
  1432. );
  1433. this.legendArea.appendChild(dot);
  1434. count++;
  1435. });
  1436. }
  1437. }
  1438. // Playing around with dates
  1439. const NO_OF_YEAR_MONTHS = 12;
  1440. const NO_OF_DAYS_IN_WEEK = 7;
  1441. const NO_OF_MILLIS = 1000;
  1442. const SEC_IN_DAY = 86400;
  1443. const MONTH_NAMES = ["January", "February", "March", "April", "May",
  1444. "June", "July", "August", "September", "October", "November", "December"];
  1445. const DAY_NAMES_SHORT = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
  1446. // https://stackoverflow.com/a/11252167/6495043
  1447. function treatAsUtc(date) {
  1448. let result = new Date(date);
  1449. result.setMinutes(result.getMinutes() - result.getTimezoneOffset());
  1450. return result;
  1451. }
  1452. function getYyyyMmDd(date) {
  1453. let dd = date.getDate();
  1454. let mm = date.getMonth() + 1; // getMonth() is zero-based
  1455. return [
  1456. date.getFullYear(),
  1457. (mm>9 ? '' : '0') + mm,
  1458. (dd>9 ? '' : '0') + dd
  1459. ].join('-');
  1460. }
  1461. function clone(date) {
  1462. return new Date(date.getTime());
  1463. }
  1464. // export function getMonthsBetween(startDate, endDate) {}
  1465. function getWeeksBetween(startDate, endDate) {
  1466. let weekStartDate = setDayToSunday(startDate);
  1467. return Math.ceil(getDaysBetween(weekStartDate, endDate) / NO_OF_DAYS_IN_WEEK);
  1468. }
  1469. function getDaysBetween(startDate, endDate) {
  1470. let millisecondsPerDay = SEC_IN_DAY * NO_OF_MILLIS;
  1471. return (treatAsUtc(endDate) - treatAsUtc(startDate)) / millisecondsPerDay;
  1472. }
  1473. function areInSameMonth(startDate, endDate) {
  1474. return startDate.getMonth() === endDate.getMonth()
  1475. && startDate.getFullYear() === endDate.getFullYear();
  1476. }
  1477. function getMonthName(i, short=false) {
  1478. let monthName = MONTH_NAMES[i];
  1479. return short ? monthName.slice(0, 3) : monthName;
  1480. }
  1481. function getLastDateInMonth (month, year) {
  1482. return new Date(year, month + 1, 0); // 0: last day in previous month
  1483. }
  1484. // mutates
  1485. function setDayToSunday(date) {
  1486. let newDate = clone(date);
  1487. const day = newDate.getDay();
  1488. if(day !== 0) {
  1489. addDays(newDate, (-1) * day);
  1490. }
  1491. return newDate;
  1492. }
  1493. // mutates
  1494. function addDays(date, numberOfDays) {
  1495. date.setDate(date.getDate() + numberOfDays);
  1496. }
  1497. class ChartComponent {
  1498. constructor({
  1499. layerClass = '',
  1500. layerTransform = '',
  1501. constants,
  1502. getData,
  1503. makeElements,
  1504. animateElements
  1505. }) {
  1506. this.layerTransform = layerTransform;
  1507. this.constants = constants;
  1508. this.makeElements = makeElements;
  1509. this.getData = getData;
  1510. this.animateElements = animateElements;
  1511. this.store = [];
  1512. this.labels = [];
  1513. this.layerClass = layerClass;
  1514. this.layerClass = typeof(this.layerClass) === 'function'
  1515. ? this.layerClass() : this.layerClass;
  1516. this.refresh();
  1517. }
  1518. refresh(data) {
  1519. this.data = data || this.getData();
  1520. }
  1521. setup(parent) {
  1522. this.layer = makeSVGGroup(this.layerClass, this.layerTransform, parent);
  1523. }
  1524. make() {
  1525. this.render(this.data);
  1526. this.oldData = this.data;
  1527. }
  1528. render(data) {
  1529. this.store = this.makeElements(data);
  1530. this.layer.textContent = '';
  1531. this.store.forEach(element => {
  1532. this.layer.appendChild(element);
  1533. });
  1534. this.labels.forEach(element => {
  1535. this.layer.appendChild(element);
  1536. });
  1537. }
  1538. update(animate = true) {
  1539. this.refresh();
  1540. let animateElements = [];
  1541. if(animate) {
  1542. animateElements = this.animateElements(this.data) || [];
  1543. }
  1544. return animateElements;
  1545. }
  1546. }
  1547. let componentConfigs = {
  1548. donutSlices: {
  1549. layerClass: 'donut-slices',
  1550. makeElements(data) {
  1551. return data.sliceStrings.map((s, i) => {
  1552. let slice = makePath(s, 'donut-path', data.colors[i], 'none', data.strokeWidth);
  1553. slice.style.transition = 'transform .3s;';
  1554. return slice;
  1555. });
  1556. },
  1557. animateElements(newData) {
  1558. return this.store.map((slice, i) => animatePathStr(slice, newData.sliceStrings[i]));
  1559. },
  1560. },
  1561. pieSlices: {
  1562. layerClass: 'pie-slices',
  1563. makeElements(data) {
  1564. return data.sliceStrings.map((s, i) =>{
  1565. let slice = makePath(s, 'pie-path', 'none', data.colors[i]);
  1566. slice.style.transition = 'transform .3s;';
  1567. return slice;
  1568. });
  1569. },
  1570. animateElements(newData) {
  1571. return this.store.map((slice, i) =>
  1572. animatePathStr(slice, newData.sliceStrings[i])
  1573. );
  1574. }
  1575. },
  1576. percentageBars: {
  1577. layerClass: 'percentage-bars',
  1578. makeElements(data) {
  1579. return data.xPositions.map((x, i) =>{
  1580. let y = 0;
  1581. let bar = percentageBar(x, y, data.widths[i],
  1582. this.constants.barHeight, this.constants.barDepth, data.colors[i]);
  1583. return bar;
  1584. });
  1585. },
  1586. animateElements(newData) {
  1587. if(newData) return [];
  1588. }
  1589. },
  1590. yAxis: {
  1591. layerClass: 'y axis',
  1592. makeElements(data) {
  1593. return data.positions.map((position, i) =>
  1594. yLine(position, data.labels[i], this.constants.width,
  1595. {mode: this.constants.mode, pos: this.constants.pos})
  1596. );
  1597. },
  1598. animateElements(newData) {
  1599. let newPos = newData.positions;
  1600. let newLabels = newData.labels;
  1601. let oldPos = this.oldData.positions;
  1602. let oldLabels = this.oldData.labels;
  1603. [oldPos, newPos] = equilizeNoOfElements(oldPos, newPos);
  1604. [oldLabels, newLabels] = equilizeNoOfElements(oldLabels, newLabels);
  1605. this.render({
  1606. positions: oldPos,
  1607. labels: newLabels
  1608. });
  1609. return this.store.map((line, i) => {
  1610. return translateHoriLine(
  1611. line, newPos[i], oldPos[i]
  1612. );
  1613. });
  1614. }
  1615. },
  1616. xAxis: {
  1617. layerClass: 'x axis',
  1618. makeElements(data) {
  1619. return data.positions.map((position, i) =>
  1620. xLine(position, data.calcLabels[i], this.constants.height,
  1621. {mode: this.constants.mode, pos: this.constants.pos})
  1622. );
  1623. },
  1624. animateElements(newData) {
  1625. let newPos = newData.positions;
  1626. let newLabels = newData.calcLabels;
  1627. let oldPos = this.oldData.positions;
  1628. let oldLabels = this.oldData.calcLabels;
  1629. [oldPos, newPos] = equilizeNoOfElements(oldPos, newPos);
  1630. [oldLabels, newLabels] = equilizeNoOfElements(oldLabels, newLabels);
  1631. this.render({
  1632. positions: oldPos,
  1633. calcLabels: newLabels
  1634. });
  1635. return this.store.map((line, i) => {
  1636. return translateVertLine(
  1637. line, newPos[i], oldPos[i]
  1638. );
  1639. });
  1640. }
  1641. },
  1642. yMarkers: {
  1643. layerClass: 'y-markers',
  1644. makeElements(data) {
  1645. return data.map(m =>
  1646. yMarker(m.position, m.label, this.constants.width,
  1647. {labelPos: m.options.labelPos, mode: 'span', lineType: 'dashed'})
  1648. );
  1649. },
  1650. animateElements(newData) {
  1651. [this.oldData, newData] = equilizeNoOfElements(this.oldData, newData);
  1652. let newPos = newData.map(d => d.position);
  1653. let newLabels = newData.map(d => d.label);
  1654. let newOptions = newData.map(d => d.options);
  1655. let oldPos = this.oldData.map(d => d.position);
  1656. this.render(oldPos.map((pos, i) => {
  1657. return {
  1658. position: oldPos[i],
  1659. label: newLabels[i],
  1660. options: newOptions[i]
  1661. };
  1662. }));
  1663. return this.store.map((line, i) => {
  1664. return translateHoriLine(
  1665. line, newPos[i], oldPos[i]
  1666. );
  1667. });
  1668. }
  1669. },
  1670. yRegions: {
  1671. layerClass: 'y-regions',
  1672. makeElements(data) {
  1673. return data.map(r =>
  1674. yRegion(r.startPos, r.endPos, this.constants.width,
  1675. r.label, {labelPos: r.options.labelPos})
  1676. );
  1677. },
  1678. animateElements(newData) {
  1679. [this.oldData, newData] = equilizeNoOfElements(this.oldData, newData);
  1680. let newPos = newData.map(d => d.endPos);
  1681. let newLabels = newData.map(d => d.label);
  1682. let newStarts = newData.map(d => d.startPos);
  1683. let newOptions = newData.map(d => d.options);
  1684. let oldPos = this.oldData.map(d => d.endPos);
  1685. let oldStarts = this.oldData.map(d => d.startPos);
  1686. this.render(oldPos.map((pos, i) => {
  1687. return {
  1688. startPos: oldStarts[i],
  1689. endPos: oldPos[i],
  1690. label: newLabels[i],
  1691. options: newOptions[i]
  1692. };
  1693. }));
  1694. let animateElements = [];
  1695. this.store.map((rectGroup, i) => {
  1696. animateElements = animateElements.concat(animateRegion(
  1697. rectGroup, newStarts[i], newPos[i], oldPos[i]
  1698. ));
  1699. });
  1700. return animateElements;
  1701. }
  1702. },
  1703. heatDomain: {
  1704. layerClass: function() { return 'heat-domain domain-' + this.constants.index; },
  1705. makeElements(data) {
  1706. let {index, colWidth, rowHeight, squareSize, xTranslate} = this.constants;
  1707. let monthNameHeight = -12;
  1708. let x = xTranslate, y = 0;
  1709. this.serializedSubDomains = [];
  1710. data.cols.map((week, weekNo) => {
  1711. if(weekNo === 1) {
  1712. this.labels.push(
  1713. makeText('domain-name', x, monthNameHeight, getMonthName(index, true).toUpperCase(),
  1714. {
  1715. fontSize: 9
  1716. }
  1717. )
  1718. );
  1719. }
  1720. week.map((day, i) => {
  1721. if(day.fill) {
  1722. let data = {
  1723. 'data-date': day.yyyyMmDd,
  1724. 'data-value': day.dataValue,
  1725. 'data-day': i
  1726. };
  1727. let square = heatSquare('day', x, y, squareSize, day.fill, data);
  1728. this.serializedSubDomains.push(square);
  1729. }
  1730. y += rowHeight;
  1731. });
  1732. y = 0;
  1733. x += colWidth;
  1734. });
  1735. return this.serializedSubDomains;
  1736. },
  1737. animateElements(newData) {
  1738. if(newData) return [];
  1739. }
  1740. },
  1741. barGraph: {
  1742. layerClass: function() { return 'dataset-units dataset-bars dataset-' + this.constants.index; },
  1743. makeElements(data) {
  1744. let c = this.constants;
  1745. this.unitType = 'bar';
  1746. this.units = data.yPositions.map((y, j) => {
  1747. return datasetBar(
  1748. data.xPositions[j],
  1749. y,
  1750. data.barWidth,
  1751. c.color,
  1752. data.labels[j],
  1753. j,
  1754. data.offsets[j],
  1755. {
  1756. zeroLine: data.zeroLine,
  1757. barsWidth: data.barsWidth,
  1758. minHeight: c.minHeight
  1759. }
  1760. );
  1761. });
  1762. return this.units;
  1763. },
  1764. animateElements(newData) {
  1765. let newXPos = newData.xPositions;
  1766. let newYPos = newData.yPositions;
  1767. let newOffsets = newData.offsets;
  1768. let newLabels = newData.labels;
  1769. let oldXPos = this.oldData.xPositions;
  1770. let oldYPos = this.oldData.yPositions;
  1771. let oldOffsets = this.oldData.offsets;
  1772. let oldLabels = this.oldData.labels;
  1773. [oldXPos, newXPos] = equilizeNoOfElements(oldXPos, newXPos);
  1774. [oldYPos, newYPos] = equilizeNoOfElements(oldYPos, newYPos);
  1775. [oldOffsets, newOffsets] = equilizeNoOfElements(oldOffsets, newOffsets);
  1776. [oldLabels, newLabels] = equilizeNoOfElements(oldLabels, newLabels);
  1777. this.render({
  1778. xPositions: oldXPos,
  1779. yPositions: oldYPos,
  1780. offsets: oldOffsets,
  1781. labels: newLabels,
  1782. zeroLine: this.oldData.zeroLine,
  1783. barsWidth: this.oldData.barsWidth,
  1784. barWidth: this.oldData.barWidth,
  1785. });
  1786. let animateElements = [];
  1787. this.store.map((bar, i) => {
  1788. animateElements = animateElements.concat(animateBar(
  1789. bar, newXPos[i], newYPos[i], newData.barWidth, newOffsets[i],
  1790. {zeroLine: newData.zeroLine}
  1791. ));
  1792. });
  1793. return animateElements;
  1794. }
  1795. },
  1796. lineGraph: {
  1797. layerClass: function() { return 'dataset-units dataset-line dataset-' + this.constants.index; },
  1798. makeElements(data) {
  1799. let c = this.constants;
  1800. this.unitType = 'dot';
  1801. this.paths = {};
  1802. if(!c.hideLine) {
  1803. this.paths = getPaths(
  1804. data.xPositions,
  1805. data.yPositions,
  1806. c.color,
  1807. {
  1808. heatline: c.heatline,
  1809. regionFill: c.regionFill
  1810. },
  1811. {
  1812. svgDefs: c.svgDefs,
  1813. zeroLine: data.zeroLine
  1814. }
  1815. );
  1816. }
  1817. this.units = [];
  1818. if(!c.hideDots) {
  1819. this.units = data.yPositions.map((y, j) => {
  1820. return datasetDot(
  1821. data.xPositions[j],
  1822. y,
  1823. data.radius,
  1824. c.color,
  1825. (c.valuesOverPoints ? data.values[j] : ''),
  1826. j
  1827. );
  1828. });
  1829. }
  1830. return Object.values(this.paths).concat(this.units);
  1831. },
  1832. animateElements(newData) {
  1833. let newXPos = newData.xPositions;
  1834. let newYPos = newData.yPositions;
  1835. let newValues = newData.values;
  1836. let oldXPos = this.oldData.xPositions;
  1837. let oldYPos = this.oldData.yPositions;
  1838. let oldValues = this.oldData.values;
  1839. [oldXPos, newXPos] = equilizeNoOfElements(oldXPos, newXPos);
  1840. [oldYPos, newYPos] = equilizeNoOfElements(oldYPos, newYPos);
  1841. [oldValues, newValues] = equilizeNoOfElements(oldValues, newValues);
  1842. this.render({
  1843. xPositions: oldXPos,
  1844. yPositions: oldYPos,
  1845. values: newValues,
  1846. zeroLine: this.oldData.zeroLine,
  1847. radius: this.oldData.radius,
  1848. });
  1849. let animateElements = [];
  1850. if(Object.keys(this.paths).length) {
  1851. animateElements = animateElements.concat(animatePath(
  1852. this.paths, newXPos, newYPos, newData.zeroLine));
  1853. }
  1854. if(this.units.length) {
  1855. this.units.map((dot, i) => {
  1856. animateElements = animateElements.concat(animateDot(
  1857. dot, newXPos[i], newYPos[i]));
  1858. });
  1859. }
  1860. return animateElements;
  1861. }
  1862. }
  1863. };
  1864. function getComponent(name, constants, getData) {
  1865. let keys = Object.keys(componentConfigs).filter(k => name.includes(k));
  1866. let config = componentConfigs[keys[0]];
  1867. Object.assign(config, {
  1868. constants: constants,
  1869. getData: getData
  1870. });
  1871. return new ChartComponent(config);
  1872. }
  1873. class PercentageChart extends AggregationChart {
  1874. constructor(parent, args) {
  1875. super(parent, args);
  1876. this.type = 'percentage';
  1877. this.setup();
  1878. }
  1879. setMeasures(options) {
  1880. let m = this.measures;
  1881. this.barOptions = options.barOptions || {};
  1882. let b = this.barOptions;
  1883. b.height = b.height || PERCENTAGE_BAR_DEFAULT_HEIGHT;
  1884. b.depth = b.depth || PERCENTAGE_BAR_DEFAULT_DEPTH;
  1885. m.paddings.right = 30;
  1886. m.legendHeight = 80;
  1887. m.baseHeight = (b.height + b.depth * 0.5) * 8;
  1888. }
  1889. setupComponents() {
  1890. let s = this.state;
  1891. let componentConfigs = [
  1892. [
  1893. 'percentageBars',
  1894. {
  1895. barHeight: this.barOptions.height,
  1896. barDepth: this.barOptions.depth,
  1897. },
  1898. function() {
  1899. return {
  1900. xPositions: s.xPositions,
  1901. widths: s.widths,
  1902. colors: this.colors
  1903. };
  1904. }.bind(this)
  1905. ]
  1906. ];
  1907. this.components = new Map(componentConfigs
  1908. .map(args => {
  1909. let component = getComponent(...args);
  1910. return [args[0], component];
  1911. }));
  1912. }
  1913. calc() {
  1914. super.calc();
  1915. let s = this.state;
  1916. s.xPositions = [];
  1917. s.widths = [];
  1918. let xPos = 0;
  1919. s.sliceTotals.map((value) => {
  1920. let width = this.width * value / s.grandTotal;
  1921. s.widths.push(width);
  1922. s.xPositions.push(xPos);
  1923. xPos += width;
  1924. });
  1925. }
  1926. makeDataByIndex() { }
  1927. bindTooltip() {
  1928. let s = this.state;
  1929. this.container.addEventListener('mousemove', (e) => {
  1930. let bars = this.components.get('percentageBars').store;
  1931. let bar = e.target;
  1932. if(bars.includes(bar)) {
  1933. let i = bars.indexOf(bar);
  1934. let gOff = getOffset(this.container), pOff = getOffset(bar);
  1935. let x = pOff.left - gOff.left + parseInt(bar.getAttribute('width'))/2;
  1936. let y = pOff.top - gOff.top;
  1937. let title = (this.formattedLabels && this.formattedLabels.length>0
  1938. ? this.formattedLabels[i] : this.state.labels[i]) + ': ';
  1939. let fraction = s.sliceTotals[i]/s.grandTotal;
  1940. this.tip.setValues(x, y, {name: title, value: (fraction*100).toFixed(1) + "%"});
  1941. this.tip.showTip();
  1942. }
  1943. });
  1944. }
  1945. }
  1946. class PieChart extends AggregationChart {
  1947. constructor(parent, args) {
  1948. super(parent, args);
  1949. this.type = 'pie';
  1950. this.initTimeout = 0;
  1951. this.init = 1;
  1952. this.setup();
  1953. }
  1954. configure(args) {
  1955. super.configure(args);
  1956. this.mouseMove = this.mouseMove.bind(this);
  1957. this.mouseLeave = this.mouseLeave.bind(this);
  1958. this.hoverRadio = args.hoverRadio || 0.1;
  1959. this.config.startAngle = args.startAngle || 0;
  1960. this.clockWise = args.clockWise || false;
  1961. }
  1962. calc() {
  1963. super.calc();
  1964. let s = this.state;
  1965. this.radius = (this.height > this.width ? this.center.x : this.center.y);
  1966. const { radius, clockWise } = this;
  1967. const prevSlicesProperties = s.slicesProperties || [];
  1968. s.sliceStrings = [];
  1969. s.slicesProperties = [];
  1970. let curAngle = 180 - this.config.startAngle;
  1971. s.sliceTotals.map((total, i) => {
  1972. const startAngle = curAngle;
  1973. const originDiffAngle = (total / s.grandTotal) * FULL_ANGLE;
  1974. const diffAngle = clockWise ? -originDiffAngle : originDiffAngle;
  1975. const endAngle = curAngle = curAngle + diffAngle;
  1976. const startPosition = getPositionByAngle(startAngle, radius);
  1977. const endPosition = getPositionByAngle(endAngle, radius);
  1978. const prevProperty = this.init && prevSlicesProperties[i];
  1979. let curStart,curEnd;
  1980. if(this.init) {
  1981. curStart = prevProperty ? prevProperty.startPosition : startPosition;
  1982. curEnd = prevProperty ? prevProperty.endPosition : startPosition;
  1983. } else {
  1984. curStart = startPosition;
  1985. curEnd = endPosition;
  1986. }
  1987. const curPath = makeArcPathStr(curStart, curEnd, this.center, this.radius, this.clockWise);
  1988. s.sliceStrings.push(curPath);
  1989. s.slicesProperties.push({
  1990. startPosition,
  1991. endPosition,
  1992. value: total,
  1993. total: s.grandTotal,
  1994. startAngle,
  1995. endAngle,
  1996. angle: diffAngle
  1997. });
  1998. });
  1999. this.init = 0;
  2000. }
  2001. setupComponents() {
  2002. let s = this.state;
  2003. let componentConfigs = [
  2004. [
  2005. 'pieSlices',
  2006. { },
  2007. function() {
  2008. return {
  2009. sliceStrings: s.sliceStrings,
  2010. colors: this.colors
  2011. };
  2012. }.bind(this)
  2013. ]
  2014. ];
  2015. this.components = new Map(componentConfigs
  2016. .map(args => {
  2017. let component = getComponent(...args);
  2018. return [args[0], component];
  2019. }));
  2020. }
  2021. calTranslateByAngle(property){
  2022. const{radius,hoverRadio} = this;
  2023. const position = getPositionByAngle(property.startAngle+(property.angle / 2),radius);
  2024. return `translate3d(${(position.x) * hoverRadio}px,${(position.y) * hoverRadio}px,0)`;
  2025. }
  2026. hoverSlice(path,i,flag,e){
  2027. if(!path) return;
  2028. const color = this.colors[i];
  2029. if(flag) {
  2030. transform(path, this.calTranslateByAngle(this.state.slicesProperties[i]));
  2031. path.style.fill = lightenDarkenColor(color, 50);
  2032. let g_off = getOffset(this.svg);
  2033. let x = e.pageX - g_off.left + 10;
  2034. let y = e.pageY - g_off.top - 10;
  2035. let title = (this.formatted_labels && this.formatted_labels.length > 0
  2036. ? this.formatted_labels[i] : this.state.labels[i]) + ': ';
  2037. let percent = (this.state.sliceTotals[i] * 100 / this.state.grandTotal).toFixed(1);
  2038. this.tip.setValues(x, y, {name: title, value: percent + "%"});
  2039. this.tip.showTip();
  2040. } else {
  2041. transform(path,'translate3d(0,0,0)');
  2042. this.tip.hideTip();
  2043. path.style.fill = color;
  2044. }
  2045. }
  2046. bindTooltip() {
  2047. this.container.addEventListener('mousemove', this.mouseMove);
  2048. this.container.addEventListener('mouseleave', this.mouseLeave);
  2049. }
  2050. mouseMove(e){
  2051. const target = e.target;
  2052. let slices = this.components.get('pieSlices').store;
  2053. let prevIndex = this.curActiveSliceIndex;
  2054. let prevAcitve = this.curActiveSlice;
  2055. if(slices.includes(target)) {
  2056. let i = slices.indexOf(target);
  2057. this.hoverSlice(prevAcitve, prevIndex,false);
  2058. this.curActiveSlice = target;
  2059. this.curActiveSliceIndex = i;
  2060. this.hoverSlice(target, i, true, e);
  2061. } else {
  2062. this.mouseLeave();
  2063. }
  2064. }
  2065. mouseLeave(){
  2066. this.hoverSlice(this.curActiveSlice,this.curActiveSliceIndex,false);
  2067. }
  2068. }
  2069. function normalize(x) {
  2070. // Calculates mantissa and exponent of a number
  2071. // Returns normalized number and exponent
  2072. // https://stackoverflow.com/q/9383593/6495043
  2073. if(x===0) {
  2074. return [0, 0];
  2075. }
  2076. if(isNaN(x)) {
  2077. return {mantissa: -6755399441055744, exponent: 972};
  2078. }
  2079. var sig = x > 0 ? 1 : -1;
  2080. if(!isFinite(x)) {
  2081. return {mantissa: sig * 4503599627370496, exponent: 972};
  2082. }
  2083. x = Math.abs(x);
  2084. var exp = Math.floor(Math.log10(x));
  2085. var man = x/Math.pow(10, exp);
  2086. return [sig * man, exp];
  2087. }
  2088. function getChartRangeIntervals(max, min=0) {
  2089. let upperBound = Math.ceil(max);
  2090. let lowerBound = Math.floor(min);
  2091. let range = upperBound - lowerBound;
  2092. let noOfParts = range;
  2093. let partSize = 1;
  2094. // To avoid too many partitions
  2095. if(range > 5) {
  2096. if(range % 2 !== 0) {
  2097. upperBound++;
  2098. // Recalc range
  2099. range = upperBound - lowerBound;
  2100. }
  2101. noOfParts = range/2;
  2102. partSize = 2;
  2103. }
  2104. // Special case: 1 and 2
  2105. if(range <= 2) {
  2106. noOfParts = 4;
  2107. partSize = range/noOfParts;
  2108. }
  2109. // Special case: 0
  2110. if(range === 0) {
  2111. noOfParts = 5;
  2112. partSize = 1;
  2113. }
  2114. let intervals = [];
  2115. for(var i = 0; i <= noOfParts; i++){
  2116. intervals.push(lowerBound + partSize * i);
  2117. }
  2118. return intervals;
  2119. }
  2120. function getChartIntervals(maxValue, minValue=0) {
  2121. let [normalMaxValue, exponent] = normalize(maxValue);
  2122. let normalMinValue = minValue ? minValue/Math.pow(10, exponent): 0;
  2123. // Allow only 7 significant digits
  2124. normalMaxValue = normalMaxValue.toFixed(6);
  2125. let intervals = getChartRangeIntervals(normalMaxValue, normalMinValue);
  2126. intervals = intervals.map(value => value * Math.pow(10, exponent));
  2127. return intervals;
  2128. }
  2129. function calcChartIntervals(values, withMinimum=false) {
  2130. //*** Where the magic happens ***
  2131. // Calculates best-fit y intervals from given values
  2132. // and returns the interval array
  2133. let maxValue = Math.max(...values);
  2134. let minValue = Math.min(...values);
  2135. // Exponent to be used for pretty print
  2136. let exponent = 0, intervals = []; // eslint-disable-line no-unused-vars
  2137. function getPositiveFirstIntervals(maxValue, absMinValue) {
  2138. let intervals = getChartIntervals(maxValue);
  2139. let intervalSize = intervals[1] - intervals[0];
  2140. // Then unshift the negative values
  2141. let value = 0;
  2142. for(var i = 1; value < absMinValue; i++) {
  2143. value += intervalSize;
  2144. intervals.unshift((-1) * value);
  2145. }
  2146. return intervals;
  2147. }
  2148. // CASE I: Both non-negative
  2149. if(maxValue >= 0 && minValue >= 0) {
  2150. exponent = normalize(maxValue)[1];
  2151. if(!withMinimum) {
  2152. intervals = getChartIntervals(maxValue);
  2153. } else {
  2154. intervals = getChartIntervals(maxValue, minValue);
  2155. }
  2156. }
  2157. // CASE II: Only minValue negative
  2158. else if(maxValue > 0 && minValue < 0) {
  2159. // `withMinimum` irrelevant in this case,
  2160. // We'll be handling both sides of zero separately
  2161. // (both starting from zero)
  2162. // Because ceil() and floor() behave differently
  2163. // in those two regions
  2164. let absMinValue = Math.abs(minValue);
  2165. if(maxValue >= absMinValue) {
  2166. exponent = normalize(maxValue)[1];
  2167. intervals = getPositiveFirstIntervals(maxValue, absMinValue);
  2168. } else {
  2169. // Mirror: maxValue => absMinValue, then change sign
  2170. exponent = normalize(absMinValue)[1];
  2171. let posIntervals = getPositiveFirstIntervals(absMinValue, maxValue);
  2172. intervals = posIntervals.map(d => d * (-1));
  2173. }
  2174. }
  2175. // CASE III: Both non-positive
  2176. else if(maxValue <= 0 && minValue <= 0) {
  2177. // Mirrored Case I:
  2178. // Work with positives, then reverse the sign and array
  2179. let pseudoMaxValue = Math.abs(minValue);
  2180. let pseudoMinValue = Math.abs(maxValue);
  2181. exponent = normalize(pseudoMaxValue)[1];
  2182. if(!withMinimum) {
  2183. intervals = getChartIntervals(pseudoMaxValue);
  2184. } else {
  2185. intervals = getChartIntervals(pseudoMaxValue, pseudoMinValue);
  2186. }
  2187. intervals = intervals.reverse().map(d => d * (-1));
  2188. }
  2189. return intervals;
  2190. }
  2191. function getZeroIndex(yPts) {
  2192. let zeroIndex;
  2193. let interval = getIntervalSize(yPts);
  2194. if(yPts.indexOf(0) >= 0) {
  2195. // the range has a given zero
  2196. // zero-line on the chart
  2197. zeroIndex = yPts.indexOf(0);
  2198. } else if(yPts[0] > 0) {
  2199. // Minimum value is positive
  2200. // zero-line is off the chart: below
  2201. let min = yPts[0];
  2202. zeroIndex = (-1) * min / interval;
  2203. } else {
  2204. // Maximum value is negative
  2205. // zero-line is off the chart: above
  2206. let max = yPts[yPts.length - 1];
  2207. zeroIndex = (-1) * max / interval + (yPts.length - 1);
  2208. }
  2209. return zeroIndex;
  2210. }
  2211. function getIntervalSize(orderedArray) {
  2212. return orderedArray[1] - orderedArray[0];
  2213. }
  2214. function getValueRange(orderedArray) {
  2215. return orderedArray[orderedArray.length-1] - orderedArray[0];
  2216. }
  2217. function scale(val, yAxis) {
  2218. return floatTwo(yAxis.zeroLine - val * yAxis.scaleMultiplier);
  2219. }
  2220. function getClosestInArray(goal, arr, index = false) {
  2221. let closest = arr.reduce(function(prev, curr) {
  2222. return (Math.abs(curr - goal) < Math.abs(prev - goal) ? curr : prev);
  2223. });
  2224. return index ? arr.indexOf(closest) : closest;
  2225. }
  2226. function calcDistribution(values, distributionSize) {
  2227. // Assume non-negative values,
  2228. // implying distribution minimum at zero
  2229. let dataMaxValue = Math.max(...values);
  2230. let distributionStep = 1 / (distributionSize - 1);
  2231. let distribution = [];
  2232. for(var i = 0; i < distributionSize; i++) {
  2233. let checkpoint = dataMaxValue * (distributionStep * i);
  2234. distribution.push(checkpoint);
  2235. }
  2236. return distribution;
  2237. }
  2238. function getMaxCheckpoint(value, distribution) {
  2239. return distribution.filter(d => d < value).length;
  2240. }
  2241. const COL_WIDTH = HEATMAP_SQUARE_SIZE + HEATMAP_GUTTER_SIZE;
  2242. const ROW_HEIGHT = COL_WIDTH;
  2243. // const DAY_INCR = 1;
  2244. class Heatmap extends BaseChart {
  2245. constructor(parent, options) {
  2246. super(parent, options);
  2247. this.type = 'heatmap';
  2248. this.countLabel = options.countLabel || '';
  2249. let validStarts = ['Sunday', 'Monday'];
  2250. let startSubDomain = validStarts.includes(options.startSubDomain)
  2251. ? options.startSubDomain : 'Sunday';
  2252. this.startSubDomainIndex = validStarts.indexOf(startSubDomain);
  2253. this.setup();
  2254. }
  2255. setMeasures(options) {
  2256. let m = this.measures;
  2257. this.discreteDomains = options.discreteDomains === 0 ? 0 : 1;
  2258. m.paddings.top = ROW_HEIGHT * 3;
  2259. m.paddings.bottom = 0;
  2260. m.legendHeight = ROW_HEIGHT * 2;
  2261. m.baseHeight = ROW_HEIGHT * NO_OF_DAYS_IN_WEEK
  2262. + getExtraHeight(m);
  2263. let d = this.data;
  2264. let spacing = this.discreteDomains ? NO_OF_YEAR_MONTHS : 0;
  2265. this.independentWidth = (getWeeksBetween(d.start, d.end)
  2266. + spacing) * COL_WIDTH + getExtraWidth(m);
  2267. }
  2268. updateWidth() {
  2269. let spacing = this.discreteDomains ? NO_OF_YEAR_MONTHS : 0;
  2270. let noOfWeeks = this.state.noOfWeeks ? this.state.noOfWeeks : 52;
  2271. this.baseWidth = (noOfWeeks + spacing) * COL_WIDTH
  2272. + getExtraWidth(this.measures);
  2273. }
  2274. prepareData(data=this.data) {
  2275. if(data.start && data.end && data.start > data.end) {
  2276. throw new Error('Start date cannot be greater than end date.');
  2277. }
  2278. if(!data.start) {
  2279. data.start = new Date();
  2280. data.start.setFullYear( data.start.getFullYear() - 1 );
  2281. }
  2282. if(!data.end) { data.end = new Date(); }
  2283. data.dataPoints = data.dataPoints || {};
  2284. if(parseInt(Object.keys(data.dataPoints)[0]) > 100000) {
  2285. let points = {};
  2286. Object.keys(data.dataPoints).forEach(timestampSec$$1 => {
  2287. let date = new Date(timestampSec$$1 * NO_OF_MILLIS);
  2288. points[getYyyyMmDd(date)] = data.dataPoints[timestampSec$$1];
  2289. });
  2290. data.dataPoints = points;
  2291. }
  2292. return data;
  2293. }
  2294. calc() {
  2295. let s = this.state;
  2296. s.start = clone(this.data.start);
  2297. s.end = clone(this.data.end);
  2298. s.firstWeekStart = clone(s.start);
  2299. s.noOfWeeks = getWeeksBetween(s.start, s.end);
  2300. s.distribution = calcDistribution(
  2301. Object.values(this.data.dataPoints), HEATMAP_DISTRIBUTION_SIZE);
  2302. s.domainConfigs = this.getDomains();
  2303. }
  2304. setupComponents() {
  2305. let s = this.state;
  2306. let lessCol = this.discreteDomains ? 0 : 1;
  2307. let componentConfigs = s.domainConfigs.map((config, i) => [
  2308. 'heatDomain',
  2309. {
  2310. index: config.index,
  2311. colWidth: COL_WIDTH,
  2312. rowHeight: ROW_HEIGHT,
  2313. squareSize: HEATMAP_SQUARE_SIZE,
  2314. xTranslate: s.domainConfigs
  2315. .filter((config, j) => j < i)
  2316. .map(config => config.cols.length - lessCol)
  2317. .reduce((a, b) => a + b, 0)
  2318. * COL_WIDTH
  2319. },
  2320. function() {
  2321. return s.domainConfigs[i];
  2322. }.bind(this)
  2323. ]);
  2324. this.components = new Map(componentConfigs
  2325. .map((args, i) => {
  2326. let component = getComponent(...args);
  2327. return [args[0] + '-' + i, component];
  2328. })
  2329. );
  2330. let y = 0;
  2331. DAY_NAMES_SHORT.forEach((dayName, i) => {
  2332. if([1, 3, 5].includes(i)) {
  2333. let dayText = makeText('subdomain-name', -COL_WIDTH/2, y, dayName,
  2334. {
  2335. fontSize: HEATMAP_SQUARE_SIZE,
  2336. dy: 8,
  2337. textAnchor: 'end'
  2338. }
  2339. );
  2340. this.drawArea.appendChild(dayText);
  2341. }
  2342. y += ROW_HEIGHT;
  2343. });
  2344. }
  2345. update(data) {
  2346. if(!data) {
  2347. console.error('No data to update.');
  2348. }
  2349. this.data = this.prepareData(data);
  2350. this.draw();
  2351. this.bindTooltip();
  2352. }
  2353. bindTooltip() {
  2354. this.container.addEventListener('mousemove', (e) => {
  2355. this.components.forEach(comp => {
  2356. let daySquares = comp.store;
  2357. let daySquare = e.target;
  2358. if(daySquares.includes(daySquare)) {
  2359. let count = daySquare.getAttribute('data-value');
  2360. let dateParts = daySquare.getAttribute('data-date').split('-');
  2361. let month = getMonthName(parseInt(dateParts[1])-1, true);
  2362. let gOff = this.container.getBoundingClientRect(), pOff = daySquare.getBoundingClientRect();
  2363. let width = parseInt(e.target.getAttribute('width'));
  2364. let x = pOff.left - gOff.left + width/2;
  2365. let y = pOff.top - gOff.top;
  2366. let value = count + ' ' + this.countLabel;
  2367. let name = ' on ' + month + ' ' + dateParts[0] + ', ' + dateParts[2];
  2368. this.tip.setValues(x, y, {name: name, value: value, valueFirst: 1}, []);
  2369. this.tip.showTip();
  2370. }
  2371. });
  2372. });
  2373. }
  2374. renderLegend() {
  2375. this.legendArea.textContent = '';
  2376. let x = 0;
  2377. let y = ROW_HEIGHT;
  2378. let lessText = makeText('subdomain-name', x, y, 'Less',
  2379. {
  2380. fontSize: HEATMAP_SQUARE_SIZE + 1,
  2381. dy: 9
  2382. }
  2383. );
  2384. x = (COL_WIDTH * 2) + COL_WIDTH/2;
  2385. this.legendArea.appendChild(lessText);
  2386. this.colors.slice(0, HEATMAP_DISTRIBUTION_SIZE).map((color, i) => {
  2387. const square = heatSquare('heatmap-legend-unit', x + (COL_WIDTH + 3) * i,
  2388. y, HEATMAP_SQUARE_SIZE, color);
  2389. this.legendArea.appendChild(square);
  2390. });
  2391. let moreTextX = x + HEATMAP_DISTRIBUTION_SIZE * (COL_WIDTH + 3) + COL_WIDTH/4;
  2392. let moreText = makeText('subdomain-name', moreTextX, y, 'More',
  2393. {
  2394. fontSize: HEATMAP_SQUARE_SIZE + 1,
  2395. dy: 9
  2396. }
  2397. );
  2398. this.legendArea.appendChild(moreText);
  2399. }
  2400. getDomains() {
  2401. let s = this.state;
  2402. const [startMonth, startYear] = [s.start.getMonth(), s.start.getFullYear()];
  2403. const [endMonth, endYear] = [s.end.getMonth(), s.end.getFullYear()];
  2404. const noOfMonths = (endMonth - startMonth + 1) + (endYear - startYear) * 12;
  2405. let domainConfigs = [];
  2406. let startOfMonth = clone(s.start);
  2407. for(var i = 0; i < noOfMonths; i++) {
  2408. let endDate = s.end;
  2409. if(!areInSameMonth(startOfMonth, s.end)) {
  2410. let [month, year] = [startOfMonth.getMonth(), startOfMonth.getFullYear()];
  2411. endDate = getLastDateInMonth(month, year);
  2412. }
  2413. domainConfigs.push(this.getDomainConfig(startOfMonth, endDate));
  2414. addDays(endDate, 1);
  2415. startOfMonth = endDate;
  2416. }
  2417. return domainConfigs;
  2418. }
  2419. getDomainConfig(startDate, endDate='') {
  2420. let [month, year] = [startDate.getMonth(), startDate.getFullYear()];
  2421. let startOfWeek = setDayToSunday(startDate); // TODO: Monday as well
  2422. endDate = clone(endDate) || getLastDateInMonth(month, year);
  2423. let domainConfig = {
  2424. index: month,
  2425. cols: []
  2426. };
  2427. addDays(endDate, 1);
  2428. let noOfMonthWeeks = getWeeksBetween(startOfWeek, endDate);
  2429. let cols = [], col;
  2430. for(var i = 0; i < noOfMonthWeeks; i++) {
  2431. col = this.getCol(startOfWeek, month);
  2432. cols.push(col);
  2433. startOfWeek = new Date(col[NO_OF_DAYS_IN_WEEK - 1].yyyyMmDd);
  2434. addDays(startOfWeek, 1);
  2435. }
  2436. if(col[NO_OF_DAYS_IN_WEEK - 1].dataValue !== undefined) {
  2437. addDays(startOfWeek, 1);
  2438. cols.push(this.getCol(startOfWeek, month, true));
  2439. }
  2440. domainConfig.cols = cols;
  2441. return domainConfig;
  2442. }
  2443. getCol(startDate, month, empty = false) {
  2444. let s = this.state;
  2445. // startDate is the start of week
  2446. let currentDate = clone(startDate);
  2447. let col = [];
  2448. for(var i = 0; i < NO_OF_DAYS_IN_WEEK; i++, addDays(currentDate, 1)) {
  2449. let config = {};
  2450. // Non-generic adjustment for entire heatmap, needs state
  2451. let currentDateWithinData = currentDate >= s.start && currentDate <= s.end;
  2452. if(empty || currentDate.getMonth() !== month || !currentDateWithinData) {
  2453. config.yyyyMmDd = getYyyyMmDd(currentDate);
  2454. } else {
  2455. config = this.getSubDomainConfig(currentDate);
  2456. }
  2457. col.push(config);
  2458. }
  2459. return col;
  2460. }
  2461. getSubDomainConfig(date) {
  2462. let yyyyMmDd = getYyyyMmDd(date);
  2463. let dataValue = this.data.dataPoints[yyyyMmDd];
  2464. let config = {
  2465. yyyyMmDd: yyyyMmDd,
  2466. dataValue: dataValue || 0,
  2467. fill: this.colors[getMaxCheckpoint(dataValue, this.state.distribution)]
  2468. };
  2469. return config;
  2470. }
  2471. }
  2472. function dataPrep(data, type) {
  2473. data.labels = data.labels || [];
  2474. let datasetLength = data.labels.length;
  2475. // Datasets
  2476. let datasets = data.datasets;
  2477. let zeroArray = new Array(datasetLength).fill(0);
  2478. if(!datasets) {
  2479. // default
  2480. datasets = [{
  2481. values: zeroArray
  2482. }];
  2483. }
  2484. datasets.map(d=> {
  2485. // Set values
  2486. if(!d.values) {
  2487. d.values = zeroArray;
  2488. } else {
  2489. // Check for non values
  2490. let vals = d.values;
  2491. vals = vals.map(val => (!isNaN(val) ? val : 0));
  2492. // Trim or extend
  2493. if(vals.length > datasetLength) {
  2494. vals = vals.slice(0, datasetLength);
  2495. } else {
  2496. vals = fillArray(vals, datasetLength - vals.length, 0);
  2497. }
  2498. }
  2499. // Set labels
  2500. //
  2501. // Set type
  2502. if(!d.chartType ) {
  2503. if(!AXIS_DATASET_CHART_TYPES.includes(type)) type === DEFAULT_AXIS_CHART_TYPE;
  2504. d.chartType = type;
  2505. }
  2506. });
  2507. // Markers
  2508. // Regions
  2509. // data.yRegions = data.yRegions || [];
  2510. if(data.yRegions) {
  2511. data.yRegions.map(d => {
  2512. if(d.end < d.start) {
  2513. [d.start, d.end] = [d.end, d.start];
  2514. }
  2515. });
  2516. }
  2517. return data;
  2518. }
  2519. function zeroDataPrep(realData) {
  2520. let datasetLength = realData.labels.length;
  2521. let zeroArray = new Array(datasetLength).fill(0);
  2522. let zeroData = {
  2523. labels: realData.labels.slice(0, -1),
  2524. datasets: realData.datasets.map(d => {
  2525. return {
  2526. name: '',
  2527. values: zeroArray.slice(0, -1),
  2528. chartType: d.chartType
  2529. };
  2530. }),
  2531. };
  2532. if(realData.yMarkers) {
  2533. zeroData.yMarkers = [
  2534. {
  2535. value: 0,
  2536. label: ''
  2537. }
  2538. ];
  2539. }
  2540. if(realData.yRegions) {
  2541. zeroData.yRegions = [
  2542. {
  2543. start: 0,
  2544. end: 0,
  2545. label: ''
  2546. }
  2547. ];
  2548. }
  2549. return zeroData;
  2550. }
  2551. function getShortenedLabels(chartWidth, labels=[], isSeries=true) {
  2552. let allowedSpace = chartWidth / labels.length;
  2553. if(allowedSpace <= 0) allowedSpace = 1;
  2554. let allowedLetters = allowedSpace / DEFAULT_CHAR_WIDTH;
  2555. let calcLabels = labels.map((label, i) => {
  2556. label += "";
  2557. if(label.length > allowedLetters) {
  2558. if(!isSeries) {
  2559. if(allowedLetters-3 > 0) {
  2560. label = label.slice(0, allowedLetters-3) + " ...";
  2561. } else {
  2562. label = label.slice(0, allowedLetters) + '..';
  2563. }
  2564. } else {
  2565. let multiple = Math.ceil(label.length/allowedLetters);
  2566. if(i % multiple !== 0) {
  2567. label = "";
  2568. }
  2569. }
  2570. }
  2571. return label;
  2572. });
  2573. return calcLabels;
  2574. }
  2575. class AxisChart extends BaseChart {
  2576. constructor(parent, args) {
  2577. super(parent, args);
  2578. this.barOptions = args.barOptions || {};
  2579. this.lineOptions = args.lineOptions || {};
  2580. this.type = args.type || 'line';
  2581. this.init = 1;
  2582. this.setup();
  2583. }
  2584. setMeasures() {
  2585. if(this.data.datasets.length <= 1) {
  2586. this.config.showLegend = 0;
  2587. this.measures.paddings.bottom = 30;
  2588. }
  2589. }
  2590. configure(options) {
  2591. super.configure(options);
  2592. options.axisOptions = options.axisOptions || {};
  2593. options.tooltipOptions = options.tooltipOptions || {};
  2594. this.config.xAxisMode = options.axisOptions.xAxisMode || 'span';
  2595. this.config.yAxisMode = options.axisOptions.yAxisMode || 'span';
  2596. this.config.xIsSeries = options.axisOptions.xIsSeries || 0;
  2597. this.config.formatTooltipX = options.tooltipOptions.formatTooltipX;
  2598. this.config.formatTooltipY = options.tooltipOptions.formatTooltipY;
  2599. this.config.valuesOverPoints = options.valuesOverPoints;
  2600. }
  2601. prepareData(data=this.data) {
  2602. return dataPrep(data, this.type);
  2603. }
  2604. prepareFirstData(data=this.data) {
  2605. return zeroDataPrep(data);
  2606. }
  2607. calc(onlyWidthChange = false) {
  2608. this.calcXPositions();
  2609. if(!onlyWidthChange) {
  2610. this.calcYAxisParameters(this.getAllYValues(), this.type === 'line');
  2611. }
  2612. this.makeDataByIndex();
  2613. }
  2614. calcXPositions() {
  2615. let s = this.state;
  2616. let labels = this.data.labels;
  2617. s.datasetLength = labels.length;
  2618. s.unitWidth = this.width/(s.datasetLength);
  2619. // Default, as per bar, and mixed. Only line will be a special case
  2620. s.xOffset = s.unitWidth/2;
  2621. // // For a pure Line Chart
  2622. // s.unitWidth = this.width/(s.datasetLength - 1);
  2623. // s.xOffset = 0;
  2624. s.xAxis = {
  2625. labels: labels,
  2626. positions: labels.map((d, i) =>
  2627. floatTwo(s.xOffset + i * s.unitWidth)
  2628. )
  2629. };
  2630. }
  2631. calcYAxisParameters(dataValues, withMinimum = 'false') {
  2632. const yPts = calcChartIntervals(dataValues, withMinimum);
  2633. const scaleMultiplier = this.height / getValueRange(yPts);
  2634. const intervalHeight = getIntervalSize(yPts) * scaleMultiplier;
  2635. const zeroLine = this.height - (getZeroIndex(yPts) * intervalHeight);
  2636. this.state.yAxis = {
  2637. labels: yPts,
  2638. positions: yPts.map(d => zeroLine - d * scaleMultiplier),
  2639. scaleMultiplier: scaleMultiplier,
  2640. zeroLine: zeroLine,
  2641. };
  2642. // Dependent if above changes
  2643. this.calcDatasetPoints();
  2644. this.calcYExtremes();
  2645. this.calcYRegions();
  2646. }
  2647. calcDatasetPoints() {
  2648. let s = this.state;
  2649. let scaleAll = values => values.map(val => scale(val, s.yAxis));
  2650. s.datasets = this.data.datasets.map((d, i) => {
  2651. let values = d.values;
  2652. let cumulativeYs = d.cumulativeYs || [];
  2653. return {
  2654. name: d.name,
  2655. index: i,
  2656. chartType: d.chartType,
  2657. values: values,
  2658. yPositions: scaleAll(values),
  2659. cumulativeYs: cumulativeYs,
  2660. cumulativeYPos: scaleAll(cumulativeYs),
  2661. };
  2662. });
  2663. }
  2664. calcYExtremes() {
  2665. let s = this.state;
  2666. if(this.barOptions.stacked) {
  2667. s.yExtremes = s.datasets[s.datasets.length - 1].cumulativeYPos;
  2668. return;
  2669. }
  2670. s.yExtremes = new Array(s.datasetLength).fill(9999);
  2671. s.datasets.map(d => {
  2672. d.yPositions.map((pos, j) => {
  2673. if(pos < s.yExtremes[j]) {
  2674. s.yExtremes[j] = pos;
  2675. }
  2676. });
  2677. });
  2678. }
  2679. calcYRegions() {
  2680. let s = this.state;
  2681. if(this.data.yMarkers) {
  2682. this.state.yMarkers = this.data.yMarkers.map(d => {
  2683. d.position = scale(d.value, s.yAxis);
  2684. if(!d.options) d.options = {};
  2685. // if(!d.label.includes(':')) {
  2686. // d.label += ': ' + d.value;
  2687. // }
  2688. return d;
  2689. });
  2690. }
  2691. if(this.data.yRegions) {
  2692. this.state.yRegions = this.data.yRegions.map(d => {
  2693. d.startPos = scale(d.start, s.yAxis);
  2694. d.endPos = scale(d.end, s.yAxis);
  2695. if(!d.options) d.options = {};
  2696. return d;
  2697. });
  2698. }
  2699. }
  2700. getAllYValues() {
  2701. let key = 'values';
  2702. if(this.barOptions.stacked) {
  2703. key = 'cumulativeYs';
  2704. let cumulative = new Array(this.state.datasetLength).fill(0);
  2705. this.data.datasets.map((d, i) => {
  2706. let values = this.data.datasets[i].values;
  2707. d[key] = cumulative = cumulative.map((c, i) => c + values[i]);
  2708. });
  2709. }
  2710. let allValueLists = this.data.datasets.map(d => d[key]);
  2711. if(this.data.yMarkers) {
  2712. allValueLists.push(this.data.yMarkers.map(d => d.value));
  2713. }
  2714. if(this.data.yRegions) {
  2715. this.data.yRegions.map(d => {
  2716. allValueLists.push([d.end, d.start]);
  2717. });
  2718. }
  2719. return [].concat(...allValueLists);
  2720. }
  2721. setupComponents() {
  2722. let componentConfigs = [
  2723. [
  2724. 'yAxis',
  2725. {
  2726. mode: this.config.yAxisMode,
  2727. width: this.width,
  2728. // pos: 'right'
  2729. },
  2730. function() {
  2731. return this.state.yAxis;
  2732. }.bind(this)
  2733. ],
  2734. [
  2735. 'xAxis',
  2736. {
  2737. mode: this.config.xAxisMode,
  2738. height: this.height,
  2739. // pos: 'right'
  2740. },
  2741. function() {
  2742. let s = this.state;
  2743. s.xAxis.calcLabels = getShortenedLabels(this.width,
  2744. s.xAxis.labels, this.config.xIsSeries);
  2745. return s.xAxis;
  2746. }.bind(this)
  2747. ],
  2748. [
  2749. 'yRegions',
  2750. {
  2751. width: this.width,
  2752. pos: 'right'
  2753. },
  2754. function() {
  2755. return this.state.yRegions;
  2756. }.bind(this)
  2757. ],
  2758. ];
  2759. let barDatasets = this.state.datasets.filter(d => d.chartType === 'bar');
  2760. let lineDatasets = this.state.datasets.filter(d => d.chartType === 'line');
  2761. let barsConfigs = barDatasets.map(d => {
  2762. let index = d.index;
  2763. return [
  2764. 'barGraph' + '-' + d.index,
  2765. {
  2766. index: index,
  2767. color: this.colors[index],
  2768. stacked: this.barOptions.stacked,
  2769. // same for all datasets
  2770. valuesOverPoints: this.config.valuesOverPoints,
  2771. minHeight: this.height * MIN_BAR_PERCENT_HEIGHT,
  2772. },
  2773. function() {
  2774. let s = this.state;
  2775. let d = s.datasets[index];
  2776. let stacked = this.barOptions.stacked;
  2777. let spaceRatio = this.barOptions.spaceRatio || BAR_CHART_SPACE_RATIO;
  2778. let barsWidth = s.unitWidth * (1 - spaceRatio);
  2779. let barWidth = barsWidth/(stacked ? 1 : barDatasets.length);
  2780. let xPositions = s.xAxis.positions.map(x => x - barsWidth/2);
  2781. if(!stacked) {
  2782. xPositions = xPositions.map(p => p + barWidth * index);
  2783. }
  2784. let labels = new Array(s.datasetLength).fill('');
  2785. if(this.config.valuesOverPoints) {
  2786. if(stacked && d.index === s.datasets.length - 1) {
  2787. labels = d.cumulativeYs;
  2788. } else {
  2789. labels = d.values;
  2790. }
  2791. }
  2792. let offsets = new Array(s.datasetLength).fill(0);
  2793. if(stacked) {
  2794. offsets = d.yPositions.map((y, j) => y - d.cumulativeYPos[j]);
  2795. }
  2796. return {
  2797. xPositions: xPositions,
  2798. yPositions: d.yPositions,
  2799. offsets: offsets,
  2800. // values: d.values,
  2801. labels: labels,
  2802. zeroLine: s.yAxis.zeroLine,
  2803. barsWidth: barsWidth,
  2804. barWidth: barWidth,
  2805. };
  2806. }.bind(this)
  2807. ];
  2808. });
  2809. let lineConfigs = lineDatasets.map(d => {
  2810. let index = d.index;
  2811. return [
  2812. 'lineGraph' + '-' + d.index,
  2813. {
  2814. index: index,
  2815. color: this.colors[index],
  2816. svgDefs: this.svgDefs,
  2817. heatline: this.lineOptions.heatline,
  2818. regionFill: this.lineOptions.regionFill,
  2819. hideDots: this.lineOptions.hideDots,
  2820. hideLine: this.lineOptions.hideLine,
  2821. // same for all datasets
  2822. valuesOverPoints: this.config.valuesOverPoints,
  2823. },
  2824. function() {
  2825. let s = this.state;
  2826. let d = s.datasets[index];
  2827. let minLine = s.yAxis.positions[0] < s.yAxis.zeroLine
  2828. ? s.yAxis.positions[0] : s.yAxis.zeroLine;
  2829. return {
  2830. xPositions: s.xAxis.positions,
  2831. yPositions: d.yPositions,
  2832. values: d.values,
  2833. zeroLine: minLine,
  2834. radius: this.lineOptions.dotSize || LINE_CHART_DOT_SIZE,
  2835. };
  2836. }.bind(this)
  2837. ];
  2838. });
  2839. let markerConfigs = [
  2840. [
  2841. 'yMarkers',
  2842. {
  2843. width: this.width,
  2844. pos: 'right'
  2845. },
  2846. function() {
  2847. return this.state.yMarkers;
  2848. }.bind(this)
  2849. ]
  2850. ];
  2851. componentConfigs = componentConfigs.concat(barsConfigs, lineConfigs, markerConfigs);
  2852. let optionals = ['yMarkers', 'yRegions'];
  2853. this.dataUnitComponents = [];
  2854. this.components = new Map(componentConfigs
  2855. .filter(args => !optionals.includes(args[0]) || this.state[args[0]])
  2856. .map(args => {
  2857. let component = getComponent(...args);
  2858. if(args[0].includes('lineGraph') || args[0].includes('barGraph')) {
  2859. this.dataUnitComponents.push(component);
  2860. }
  2861. return [args[0], component];
  2862. }));
  2863. }
  2864. makeDataByIndex() {
  2865. this.dataByIndex = {};
  2866. let s = this.state;
  2867. let formatX = this.config.formatTooltipX;
  2868. let formatY = this.config.formatTooltipY;
  2869. let titles = s.xAxis.labels;
  2870. titles.map((label, index) => {
  2871. let values = this.state.datasets.map((set, i) => {
  2872. let value = set.values[index];
  2873. return {
  2874. title: set.name,
  2875. value: value,
  2876. yPos: set.yPositions[index],
  2877. color: this.colors[i],
  2878. formatted: formatY ? formatY(value) : value,
  2879. };
  2880. });
  2881. this.dataByIndex[index] = {
  2882. label: label,
  2883. formattedLabel: formatX ? formatX(label) : label,
  2884. xPos: s.xAxis.positions[index],
  2885. values: values,
  2886. yExtreme: s.yExtremes[index],
  2887. };
  2888. });
  2889. }
  2890. bindTooltip() {
  2891. // NOTE: could be in tooltip itself, as it is a given functionality for its parent
  2892. this.container.addEventListener('mousemove', (e) => {
  2893. let m = this.measures;
  2894. let o = getOffset(this.container);
  2895. let relX = e.pageX - o.left - getLeftOffset(m);
  2896. let relY = e.pageY - o.top;
  2897. if(relY < this.height + getTopOffset(m)
  2898. && relY > getTopOffset(m)) {
  2899. this.mapTooltipXPosition(relX);
  2900. } else {
  2901. this.tip.hideTip();
  2902. }
  2903. });
  2904. }
  2905. mapTooltipXPosition(relX) {
  2906. let s = this.state;
  2907. if(!s.yExtremes) return;
  2908. let index = getClosestInArray(relX, s.xAxis.positions, true);
  2909. let dbi = this.dataByIndex[index];
  2910. this.tip.setValues(
  2911. dbi.xPos + this.tip.offset.x,
  2912. dbi.yExtreme + this.tip.offset.y,
  2913. {name: dbi.formattedLabel, value: ''},
  2914. dbi.values,
  2915. index
  2916. );
  2917. this.tip.showTip();
  2918. }
  2919. renderLegend() {
  2920. let s = this.data;
  2921. if(s.datasets.length > 1) {
  2922. this.legendArea.textContent = '';
  2923. s.datasets.map((d, i) => {
  2924. let barWidth = AXIS_LEGEND_BAR_SIZE;
  2925. // let rightEndPoint = this.baseWidth - this.measures.margins.left - this.measures.margins.right;
  2926. // let multiplier = s.datasets.length - i;
  2927. let rect = legendBar(
  2928. // rightEndPoint - multiplier * barWidth, // To right align
  2929. barWidth * i,
  2930. '0',
  2931. barWidth,
  2932. this.colors[i],
  2933. d.name);
  2934. this.legendArea.appendChild(rect);
  2935. });
  2936. }
  2937. }
  2938. // Overlay
  2939. makeOverlay() {
  2940. if(this.init) {
  2941. this.init = 0;
  2942. return;
  2943. }
  2944. if(this.overlayGuides) {
  2945. this.overlayGuides.forEach(g => {
  2946. let o = g.overlay;
  2947. o.parentNode.removeChild(o);
  2948. });
  2949. }
  2950. this.overlayGuides = this.dataUnitComponents.map(c => {
  2951. return {
  2952. type: c.unitType,
  2953. overlay: undefined,
  2954. units: c.units,
  2955. };
  2956. });
  2957. if(this.state.currentIndex === undefined) {
  2958. this.state.currentIndex = this.state.datasetLength - 1;
  2959. }
  2960. // Render overlays
  2961. this.overlayGuides.map(d => {
  2962. let currentUnit = d.units[this.state.currentIndex];
  2963. d.overlay = makeOverlay[d.type](currentUnit);
  2964. this.drawArea.appendChild(d.overlay);
  2965. });
  2966. }
  2967. updateOverlayGuides() {
  2968. if(this.overlayGuides) {
  2969. this.overlayGuides.forEach(g => {
  2970. let o = g.overlay;
  2971. o.parentNode.removeChild(o);
  2972. });
  2973. }
  2974. }
  2975. bindOverlay() {
  2976. this.parent.addEventListener('data-select', () => {
  2977. this.updateOverlay();
  2978. });
  2979. }
  2980. bindUnits() {
  2981. this.dataUnitComponents.map(c => {
  2982. c.units.map(unit => {
  2983. unit.addEventListener('click', () => {
  2984. let index = unit.getAttribute('data-point-index');
  2985. this.setCurrentDataPoint(index);
  2986. });
  2987. });
  2988. });
  2989. // Note: Doesn't work as tooltip is absolutely positioned
  2990. this.tip.container.addEventListener('click', () => {
  2991. let index = this.tip.container.getAttribute('data-point-index');
  2992. this.setCurrentDataPoint(index);
  2993. });
  2994. }
  2995. updateOverlay() {
  2996. this.overlayGuides.map(d => {
  2997. let currentUnit = d.units[this.state.currentIndex];
  2998. updateOverlay[d.type](currentUnit, d.overlay);
  2999. });
  3000. }
  3001. onLeftArrow() {
  3002. this.setCurrentDataPoint(this.state.currentIndex - 1);
  3003. }
  3004. onRightArrow() {
  3005. this.setCurrentDataPoint(this.state.currentIndex + 1);
  3006. }
  3007. getDataPoint(index=this.state.currentIndex) {
  3008. let s = this.state;
  3009. let data_point = {
  3010. index: index,
  3011. label: s.xAxis.labels[index],
  3012. values: s.datasets.map(d => d.values[index])
  3013. };
  3014. return data_point;
  3015. }
  3016. setCurrentDataPoint(index) {
  3017. let s = this.state;
  3018. index = parseInt(index);
  3019. if(index < 0) index = 0;
  3020. if(index >= s.xAxis.labels.length) index = s.xAxis.labels.length - 1;
  3021. if(index === s.currentIndex) return;
  3022. s.currentIndex = index;
  3023. fire(this.parent, "data-select", this.getDataPoint());
  3024. }
  3025. // API
  3026. addDataPoint(label, datasetValues, index=this.state.datasetLength) {
  3027. super.addDataPoint(label, datasetValues, index);
  3028. this.data.labels.splice(index, 0, label);
  3029. this.data.datasets.map((d, i) => {
  3030. d.values.splice(index, 0, datasetValues[i]);
  3031. });
  3032. this.update(this.data);
  3033. }
  3034. removeDataPoint(index = this.state.datasetLength-1) {
  3035. if (this.data.labels.length <= 1) {
  3036. return;
  3037. }
  3038. super.removeDataPoint(index);
  3039. this.data.labels.splice(index, 1);
  3040. this.data.datasets.map(d => {
  3041. d.values.splice(index, 1);
  3042. });
  3043. this.update(this.data);
  3044. }
  3045. updateDataset(datasetValues, index=0) {
  3046. this.data.datasets[index].values = datasetValues;
  3047. this.update(this.data);
  3048. }
  3049. // addDataset(dataset, index) {}
  3050. // removeDataset(index = 0) {}
  3051. updateDatasets(datasets) {
  3052. this.data.datasets.map((d, i) => {
  3053. if(datasets[i]) {
  3054. d.values = datasets[i];
  3055. }
  3056. });
  3057. this.update(this.data);
  3058. }
  3059. // updateDataPoint(dataPoint, index = 0) {}
  3060. // addDataPoint(dataPoint, index = 0) {}
  3061. // removeDataPoint(index = 0) {}
  3062. }
  3063. class DonutChart extends AggregationChart {
  3064. constructor(parent, args) {
  3065. super(parent, args);
  3066. this.type = 'donut';
  3067. this.initTimeout = 0;
  3068. this.init = 1;
  3069. this.setup();
  3070. }
  3071. configure(args) {
  3072. super.configure(args);
  3073. this.mouseMove = this.mouseMove.bind(this);
  3074. this.mouseLeave = this.mouseLeave.bind(this);
  3075. this.hoverRadio = args.hoverRadio || 0.1;
  3076. this.config.startAngle = args.startAngle || 0;
  3077. this.clockWise = args.clockWise || false;
  3078. this.strokeWidth = args.strokeWidth || 30;
  3079. }
  3080. calc() {
  3081. super.calc();
  3082. let s = this.state;
  3083. this.radius = (this.height > this.width ? this.center.x - (this.strokeWidth / 2) : this.center.y - (this.strokeWidth / 2));
  3084. const { radius, clockWise } = this;
  3085. const prevSlicesProperties = s.slicesProperties || [];
  3086. s.sliceStrings = [];
  3087. s.slicesProperties = [];
  3088. let curAngle = 180 - this.config.startAngle;
  3089. s.sliceTotals.map((total, i) => {
  3090. const startAngle = curAngle;
  3091. const originDiffAngle = (total / s.grandTotal) * FULL_ANGLE;
  3092. const diffAngle = clockWise ? -originDiffAngle : originDiffAngle;
  3093. const endAngle = curAngle = curAngle + diffAngle;
  3094. const startPosition = getPositionByAngle(startAngle, radius);
  3095. const endPosition = getPositionByAngle(endAngle, radius);
  3096. const prevProperty = this.init && prevSlicesProperties[i];
  3097. let curStart,curEnd;
  3098. if(this.init) {
  3099. curStart = prevProperty ? prevProperty.startPosition : startPosition;
  3100. curEnd = prevProperty ? prevProperty.endPosition : startPosition;
  3101. } else {
  3102. curStart = startPosition;
  3103. curEnd = endPosition;
  3104. }
  3105. const curPath = makeArcStrokePathStr(curStart, curEnd, this.center, this.radius, this.clockWise);
  3106. s.sliceStrings.push(curPath);
  3107. s.slicesProperties.push({
  3108. startPosition,
  3109. endPosition,
  3110. value: total,
  3111. total: s.grandTotal,
  3112. startAngle,
  3113. endAngle,
  3114. angle: diffAngle
  3115. });
  3116. });
  3117. this.init = 0;
  3118. }
  3119. setupComponents() {
  3120. let s = this.state;
  3121. let componentConfigs = [
  3122. [
  3123. 'donutSlices',
  3124. { },
  3125. function() {
  3126. return {
  3127. sliceStrings: s.sliceStrings,
  3128. colors: this.colors,
  3129. strokeWidth: this.strokeWidth,
  3130. };
  3131. }.bind(this)
  3132. ]
  3133. ];
  3134. this.components = new Map(componentConfigs
  3135. .map(args => {
  3136. let component = getComponent(...args);
  3137. return [args[0], component];
  3138. }));
  3139. }
  3140. calTranslateByAngle(property){
  3141. const{radius,hoverRadio} = this;
  3142. const position = getPositionByAngle(property.startAngle+(property.angle / 2),radius);
  3143. return `translate3d(${(position.x) * hoverRadio}px,${(position.y) * hoverRadio}px,0)`;
  3144. }
  3145. hoverSlice(path,i,flag,e){
  3146. if(!path) return;
  3147. const color = this.colors[i];
  3148. if(flag) {
  3149. transform(path, this.calTranslateByAngle(this.state.slicesProperties[i]));
  3150. path.style.stroke = lightenDarkenColor(color, 50);
  3151. let g_off = getOffset(this.svg);
  3152. let x = e.pageX - g_off.left + 10;
  3153. let y = e.pageY - g_off.top - 10;
  3154. let title = (this.formatted_labels && this.formatted_labels.length > 0
  3155. ? this.formatted_labels[i] : this.state.labels[i]) + ': ';
  3156. let percent = (this.state.sliceTotals[i] * 100 / this.state.grandTotal).toFixed(1);
  3157. this.tip.setValues(x, y, {name: title, value: percent + "%"});
  3158. this.tip.showTip();
  3159. } else {
  3160. transform(path,'translate3d(0,0,0)');
  3161. this.tip.hideTip();
  3162. path.style.stroke = color;
  3163. }
  3164. }
  3165. bindTooltip() {
  3166. this.container.addEventListener('mousemove', this.mouseMove);
  3167. this.container.addEventListener('mouseleave', this.mouseLeave);
  3168. }
  3169. mouseMove(e){
  3170. const target = e.target;
  3171. let slices = this.components.get('donutSlices').store;
  3172. let prevIndex = this.curActiveSliceIndex;
  3173. let prevAcitve = this.curActiveSlice;
  3174. if(slices.includes(target)) {
  3175. let i = slices.indexOf(target);
  3176. this.hoverSlice(prevAcitve, prevIndex,false);
  3177. this.curActiveSlice = target;
  3178. this.curActiveSliceIndex = i;
  3179. this.hoverSlice(target, i, true, e);
  3180. } else {
  3181. this.mouseLeave();
  3182. }
  3183. }
  3184. mouseLeave(){
  3185. this.hoverSlice(this.curActiveSlice,this.curActiveSliceIndex,false);
  3186. }
  3187. }
  3188. // import MultiAxisChart from './charts/MultiAxisChart';
  3189. const chartTypes = {
  3190. bar: AxisChart,
  3191. line: AxisChart,
  3192. // multiaxis: MultiAxisChart,
  3193. percentage: PercentageChart,
  3194. heatmap: Heatmap,
  3195. pie: PieChart,
  3196. donut: DonutChart,
  3197. };
  3198. function getChartByType(chartType = 'line', parent, options) {
  3199. if (chartType === 'axis-mixed') {
  3200. options.type = 'line';
  3201. return new AxisChart(parent, options);
  3202. }
  3203. if (!chartTypes[chartType]) {
  3204. console.error("Undefined chart type: " + chartType);
  3205. return;
  3206. }
  3207. return new chartTypes[chartType](parent, options);
  3208. }
  3209. class Chart {
  3210. constructor(parent, options) {
  3211. return getChartByType(options.type, parent, options);
  3212. }
  3213. }
  3214. export { Chart, PercentageChart, PieChart, Heatmap, AxisChart };