Du kannst nicht mehr als 25 Themen auswählen Themen müssen entweder mit einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.
 
 
 

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