選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。
 
 
 

4337 行
128 KiB

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