25개 이상의 토픽을 선택하실 수 없습니다. Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

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