Não pode escolher mais do que 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.
 
 
 

4332 linhas
128 KiB

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