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.
 
 
 

4329 linhas
128 KiB

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