25'ten fazla konu seçemezsiniz Konular bir harf veya rakamla başlamalı, kısa çizgiler ('-') içerebilir ve en fazla 35 karakter uzunluğunda olabilir.
 
 
 

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