You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

5666 regels
161 KiB

  1. (function () {
  2. 'use strict';
  3. var asyncGenerator = function () {
  4. function AwaitValue(value) {
  5. this.value = value;
  6. }
  7. function AsyncGenerator(gen) {
  8. var front, back;
  9. function send(key, arg) {
  10. return new Promise(function (resolve, reject) {
  11. var request = {
  12. key: key,
  13. arg: arg,
  14. resolve: resolve,
  15. reject: reject,
  16. next: null
  17. };
  18. if (back) {
  19. back = back.next = request;
  20. } else {
  21. front = back = request;
  22. resume(key, arg);
  23. }
  24. });
  25. }
  26. function resume(key, arg) {
  27. try {
  28. var result = gen[key](arg);
  29. var value = result.value;
  30. if (value instanceof AwaitValue) {
  31. Promise.resolve(value.value).then(function (arg) {
  32. resume("next", arg);
  33. }, function (arg) {
  34. resume("throw", arg);
  35. });
  36. } else {
  37. settle(result.done ? "return" : "normal", result.value);
  38. }
  39. } catch (err) {
  40. settle("throw", err);
  41. }
  42. }
  43. function settle(type, value) {
  44. switch (type) {
  45. case "return":
  46. front.resolve({
  47. value: value,
  48. done: true
  49. });
  50. break;
  51. case "throw":
  52. front.reject(value);
  53. break;
  54. default:
  55. front.resolve({
  56. value: value,
  57. done: false
  58. });
  59. break;
  60. }
  61. front = front.next;
  62. if (front) {
  63. resume(front.key, front.arg);
  64. } else {
  65. back = null;
  66. }
  67. }
  68. this._invoke = send;
  69. if (typeof gen.return !== "function") {
  70. this.return = undefined;
  71. }
  72. }
  73. if (typeof Symbol === "function" && Symbol.asyncIterator) {
  74. AsyncGenerator.prototype[Symbol.asyncIterator] = function () {
  75. return this;
  76. };
  77. }
  78. AsyncGenerator.prototype.next = function (arg) {
  79. return this._invoke("next", arg);
  80. };
  81. AsyncGenerator.prototype.throw = function (arg) {
  82. return this._invoke("throw", arg);
  83. };
  84. AsyncGenerator.prototype.return = function (arg) {
  85. return this._invoke("return", arg);
  86. };
  87. return {
  88. wrap: function (fn) {
  89. return function () {
  90. return new AsyncGenerator(fn.apply(this, arguments));
  91. };
  92. },
  93. await: function (value) {
  94. return new AwaitValue(value);
  95. }
  96. };
  97. }();
  98. 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; };
  99. function $(expr, con) {
  100. return typeof expr === "string" ? (con || document).querySelector(expr) : expr || null;
  101. }
  102. $.create = function (tag, o) {
  103. var element = document.createElement(tag);
  104. for (var i in o) {
  105. var val = o[i];
  106. if (i === "inside") {
  107. $(val).appendChild(element);
  108. } else if (i === "around") {
  109. var ref = $(val);
  110. ref.parentNode.insertBefore(element, ref);
  111. element.appendChild(ref);
  112. } else if (i === "onClick") {
  113. element.addEventListener('click', val);
  114. } else if (i === "onInput") {
  115. element.addEventListener('input', function (e) {
  116. val(element.value);
  117. });
  118. } else if (i === "styles") {
  119. if ((typeof val === "undefined" ? "undefined" : _typeof(val)) === "object") {
  120. Object.keys(val).map(function (prop) {
  121. element.style[prop] = val[prop];
  122. });
  123. }
  124. } else if (i in element) {
  125. element[i] = val;
  126. } else {
  127. element.setAttribute(i, val);
  128. }
  129. }
  130. return element;
  131. };
  132. // https://css-tricks.com/snippets/javascript/loop-queryselectorall-matches/
  133. function insertAfter(newNode, referenceNode) {
  134. referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling);
  135. }
  136. // Fixed 5-color theme,
  137. // More colors are difficult to parse visually
  138. var HEATMAP_COLORS_BLUE = ['#ebedf0', '#c0ddf9', '#73b3f3', '#3886e1', '#17459e'];
  139. var HEATMAP_COLORS_YELLOW = ['#ebedf0', '#fdf436', '#ffc700', '#ff9100', '#06001c'];
  140. // Universal constants
  141. /**
  142. * Returns the value of a number upto 2 decimal places.
  143. * @param {Number} d Any number
  144. */
  145. /**
  146. * Returns whether or not two given arrays are equal.
  147. * @param {Array} arr1 First array
  148. * @param {Array} arr2 Second array
  149. */
  150. /**
  151. * Shuffles array in place. ES6 version
  152. * @param {Array} array An array containing the items.
  153. */
  154. function shuffle(array) {
  155. // Awesomeness: https://bost.ocks.org/mike/shuffle/
  156. // https://stackoverflow.com/a/2450976/6495043
  157. // https://stackoverflow.com/questions/6274339/how-can-i-shuffle-an-array?noredirect=1&lq=1
  158. for (var i = array.length - 1; i > 0; i--) {
  159. var j = Math.floor(Math.random() * (i + 1));
  160. var _ref = [array[j], array[i]];
  161. array[i] = _ref[0];
  162. array[j] = _ref[1];
  163. }
  164. return array;
  165. }
  166. /**
  167. * Fill an array with extra points
  168. * @param {Array} array Array
  169. * @param {Number} count number of filler elements
  170. * @param {Object} element element to fill with
  171. * @param {Boolean} start fill at start?
  172. */
  173. /**
  174. * Returns pixel width of string.
  175. * @param {String} string
  176. * @param {Number} charWidth Width of single char in pixels
  177. */
  178. // https://stackoverflow.com/a/29325222
  179. function getRandomBias(min, max, bias, influence) {
  180. var range = max - min;
  181. var biasValue = range * bias + min;
  182. var rnd = Math.random() * range + min,
  183. // random in range
  184. mix = Math.random() * influence; // random mixer
  185. return rnd * (1 - mix) + biasValue * mix; // mix full range and bias
  186. }
  187. function toTitleCase(str) {
  188. return str.replace(/\w*/g, function (txt) {
  189. return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();
  190. });
  191. }
  192. 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; }; }();
  193. 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); } }
  194. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  195. var docsBuilder = function () {
  196. function docsBuilder(LIB_OBJ) {
  197. _classCallCheck(this, docsBuilder);
  198. this.LIB_OBJ = LIB_OBJ;
  199. }
  200. _createClass(docsBuilder, [{
  201. key: 'makeSection',
  202. value: function makeSection(parent, sys) {
  203. return new docSection(this.LIB_OBJ, parent, sys);
  204. }
  205. }]);
  206. return docsBuilder;
  207. }();
  208. var docSection = function () {
  209. function docSection(LIB_OBJ, parent, sys) {
  210. _classCallCheck(this, docSection);
  211. this.LIB_OBJ = LIB_OBJ;
  212. this.parent = parent; // should be preferably a section
  213. this.sys = sys;
  214. this.blockMap = {};
  215. this.demos = [];
  216. this.make();
  217. }
  218. _createClass(docSection, [{
  219. key: 'make',
  220. value: function make() {
  221. var _this = this;
  222. // const section = document.querySelector(this.parent);
  223. var s = this.sys;
  224. if (s.title) {
  225. $.create('h6', { inside: this.parent, innerHTML: s.title });
  226. }
  227. if (s.contentBlocks) {
  228. s.contentBlocks.forEach(function (blockConf, index) {
  229. _this.blockMap[index] = _this.getBlock(blockConf);
  230. });
  231. } else {
  232. // TODO:
  233. this.blockMap['test'] = this.getDemo(s);
  234. }
  235. }
  236. }, {
  237. key: 'getBlock',
  238. value: function getBlock(blockConf) {
  239. var fnName = 'get' + toTitleCase(blockConf.type);
  240. if (this[fnName]) {
  241. return this[fnName](blockConf);
  242. } else {
  243. throw new Error('Unknown section block type \'' + blockConf.type + '\'.');
  244. }
  245. }
  246. }, {
  247. key: 'getText',
  248. value: function getText(blockConf) {
  249. return $.create('p', {
  250. inside: this.parent,
  251. className: 'new-context',
  252. innerHTML: blockConf.content
  253. });
  254. }
  255. }, {
  256. key: 'getCode',
  257. value: function getCode(blockConf) {
  258. var pre = $.create('pre', { inside: this.parent });
  259. var lang = blockConf.lang || 'javascript';
  260. var code = $.create('code', {
  261. inside: pre,
  262. className: 'hljs ' + lang,
  263. innerHTML: blockConf.content
  264. });
  265. }
  266. }, {
  267. key: 'getCustom',
  268. value: function getCustom(blockConf) {
  269. this.parent.innerHTML += blockConf.html;
  270. }
  271. }, {
  272. key: 'getDemo',
  273. value: function getDemo(blockConf) {
  274. var bc = blockConf;
  275. var args = bc.config;
  276. var figure = void 0,
  277. row = void 0;
  278. if (!bc.sideContent) {
  279. figure = $.create('figure', { inside: this.parent });
  280. } else {
  281. row = $.create('div', {
  282. inside: this.parent,
  283. className: "row",
  284. innerHTML: '<div class="col-sm-8"></div>\n\t\t\t\t\t<div class="col-sm-4"></div>'
  285. });
  286. figure = $.create('figure', { inside: row.querySelector('.col-sm-8') });
  287. row.querySelector('.col-sm-4').innerHTML += bc.sideContent;
  288. }
  289. var libObj = new this.LIB_OBJ(figure, args);
  290. var demoIndex = this.demos.length;
  291. this.demos.push(libObj);
  292. if (bc.postSetup) {
  293. bc.postSetup(this.demos[demoIndex], figure, row);
  294. }
  295. this.getDemoOptions(demoIndex, bc.options, args, figure);
  296. this.getDemoActions(demoIndex, bc.actions, args);
  297. }
  298. }, {
  299. key: 'getDemoOptions',
  300. value: function getDemoOptions(demoIndex) {
  301. var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [];
  302. var _this2 = this;
  303. var args = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
  304. var figure = arguments[3];
  305. options.forEach(function (o) {
  306. var btnGroup = $.create('div', {
  307. inside: _this2.parent,
  308. className: 'btn-group ' + o.name
  309. });
  310. var mapKeys = o.mapKeys;
  311. if (o.type === "number") {
  312. var numOpts = o.numberOptions;
  313. var inputGroup = $.create('input', {
  314. inside: btnGroup,
  315. className: 'form-control',
  316. type: "range",
  317. min: numOpts.min,
  318. max: numOpts.max,
  319. step: numOpts.step,
  320. value: o.activeState ? o.activeState : 0,
  321. // (max - min)/2
  322. onInput: function onInput(value) {
  323. args[o.path[0]][o.path[1]] = value;
  324. _this2.demos[demoIndex] = new _this2.LIB_OBJ(figure, args);
  325. }
  326. });
  327. } else if (["map", "string"].includes(o.type)) {
  328. args[o.path[0]] = {};
  329. Object.keys(o.states).forEach(function (key) {
  330. var state = o.states[key];
  331. var activeClass = key === o.activeState ? 'active' : '';
  332. var button = $.create('button', {
  333. inside: btnGroup,
  334. className: 'btn btn-sm btn-secondary ' + activeClass,
  335. innerHTML: key,
  336. onClick: function onClick(e) {
  337. // map
  338. if (o.type === "map") {
  339. mapKeys.forEach(function (attr, i) {
  340. args[o.path[0]][attr] = state[i];
  341. });
  342. } else {
  343. // boolean, string, number, object
  344. args[o.path[0]] = state;
  345. }
  346. _this2.demos[demoIndex] = new _this2.LIB_OBJ(figure, args);
  347. }
  348. });
  349. if (activeClass) {
  350. button.click();
  351. }
  352. });
  353. }
  354. });
  355. }
  356. }, {
  357. key: 'getDemoActions',
  358. value: function getDemoActions(demoIndex) {
  359. var _this3 = this;
  360. var actions = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [];
  361. actions.forEach(function (o) {
  362. var args = o.args || [];
  363. $.create('button', {
  364. inside: _this3.parent,
  365. className: 'btn btn-action btn-sm btn-secondary',
  366. innerHTML: o.name,
  367. onClick: function onClick() {
  368. var _demos$demoIndex;
  369. (_demos$demoIndex = _this3.demos[demoIndex])[o.fn].apply(_demos$demoIndex, _toConsumableArray(args));
  370. }
  371. });
  372. });
  373. }
  374. }]);
  375. return docSection;
  376. }();
  377. var _typeof2 = 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; };
  378. function __$styleInject(css, ref) {
  379. if (ref === void 0) ref = {};
  380. var insertAt = ref.insertAt;
  381. if (!css || typeof document === 'undefined') {
  382. return;
  383. }
  384. var head = document.head || document.getElementsByTagName('head')[0];
  385. var style = document.createElement('style');
  386. style.type = 'text/css';
  387. if (insertAt === 'top') {
  388. if (head.firstChild) {
  389. head.insertBefore(style, head.firstChild);
  390. } else {
  391. head.appendChild(style);
  392. }
  393. } else {
  394. head.appendChild(style);
  395. }
  396. if (style.styleSheet) {
  397. style.styleSheet.cssText = css;
  398. } else {
  399. style.appendChild(document.createTextNode(css));
  400. }
  401. }
  402. __$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}", {});
  403. var asyncGenerator$1 = function () {
  404. function AwaitValue(value) {
  405. this.value = value;
  406. }
  407. function AsyncGenerator(gen) {
  408. var front, back;
  409. function send(key, arg) {
  410. return new Promise(function (resolve, reject) {
  411. var request = {
  412. key: key,
  413. arg: arg,
  414. resolve: resolve,
  415. reject: reject,
  416. next: null
  417. };
  418. if (back) {
  419. back = back.next = request;
  420. } else {
  421. front = back = request;
  422. resume(key, arg);
  423. }
  424. });
  425. }
  426. function resume(key, arg) {
  427. try {
  428. var result = gen[key](arg);
  429. var value = result.value;
  430. if (value instanceof AwaitValue) {
  431. Promise.resolve(value.value).then(function (arg) {
  432. resume("next", arg);
  433. }, function (arg) {
  434. resume("throw", arg);
  435. });
  436. } else {
  437. settle(result.done ? "return" : "normal", result.value);
  438. }
  439. } catch (err) {
  440. settle("throw", err);
  441. }
  442. }
  443. function settle(type, value) {
  444. switch (type) {
  445. case "return":
  446. front.resolve({
  447. value: value,
  448. done: true
  449. });
  450. break;
  451. case "throw":
  452. front.reject(value);
  453. break;
  454. default:
  455. front.resolve({
  456. value: value,
  457. done: false
  458. });
  459. break;
  460. }
  461. front = front.next;
  462. if (front) {
  463. resume(front.key, front.arg);
  464. } else {
  465. back = null;
  466. }
  467. }
  468. this._invoke = send;
  469. if (typeof gen.return !== "function") {
  470. this.return = undefined;
  471. }
  472. }
  473. if (typeof Symbol === "function" && Symbol.asyncIterator) {
  474. AsyncGenerator.prototype[Symbol.asyncIterator] = function () {
  475. return this;
  476. };
  477. }
  478. AsyncGenerator.prototype.next = function (arg) {
  479. return this._invoke("next", arg);
  480. };
  481. AsyncGenerator.prototype.throw = function (arg) {
  482. return this._invoke("throw", arg);
  483. };
  484. AsyncGenerator.prototype.return = function (arg) {
  485. return this._invoke("return", arg);
  486. };
  487. return {
  488. wrap: function wrap(fn) {
  489. return function () {
  490. return new AsyncGenerator(fn.apply(this, arguments));
  491. };
  492. },
  493. await: function _await(value) {
  494. return new AwaitValue(value);
  495. }
  496. };
  497. }();
  498. var _typeof$2 = typeof Symbol === "function" && _typeof2(Symbol.iterator) === "symbol" ? function (obj) {
  499. return typeof obj === 'undefined' ? 'undefined' : _typeof2(obj);
  500. } : function (obj) {
  501. return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj === 'undefined' ? 'undefined' : _typeof2(obj);
  502. };
  503. function $$1(expr, con) {
  504. return typeof expr === "string" ? (con || document).querySelector(expr) : expr || null;
  505. }
  506. $$1.create = function (tag, o) {
  507. var element = document.createElement(tag);
  508. for (var i in o) {
  509. var val = o[i];
  510. if (i === "inside") {
  511. $$1(val).appendChild(element);
  512. } else if (i === "around") {
  513. var ref = $$1(val);
  514. ref.parentNode.insertBefore(element, ref);
  515. element.appendChild(ref);
  516. } else if (i === "onClick") {
  517. element.addEventListener('click', val);
  518. } else if (i === "onInput") {
  519. element.addEventListener('input', function (e) {
  520. val(element.value);
  521. });
  522. } else if (i === "styles") {
  523. if ((typeof val === "undefined" ? "undefined" : _typeof$2(val)) === "object") {
  524. Object.keys(val).map(function (prop) {
  525. element.style[prop] = val[prop];
  526. });
  527. }
  528. } else if (i in element) {
  529. element[i] = val;
  530. } else {
  531. element.setAttribute(i, val);
  532. }
  533. }
  534. return element;
  535. };
  536. function getOffset$1(element) {
  537. var rect = element.getBoundingClientRect();
  538. return {
  539. // https://stackoverflow.com/a/7436602/6495043
  540. // rect.top varies with scroll, so we add whatever has been
  541. // scrolled to it to get absolute distance from actual page top
  542. top: rect.top + (document.documentElement.scrollTop || document.body.scrollTop),
  543. left: rect.left + (document.documentElement.scrollLeft || document.body.scrollLeft)
  544. };
  545. }
  546. function isElementInViewport$1(el) {
  547. // Although straightforward: https://stackoverflow.com/a/7557433/6495043
  548. var rect = el.getBoundingClientRect();
  549. return rect.top >= 0 && rect.left >= 0 && rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) && /*or $(window).height() */
  550. rect.right <= (window.innerWidth || document.documentElement.clientWidth) /*or $(window).width() */
  551. ;
  552. }
  553. function getElementContentWidth$1(element) {
  554. var styles = window.getComputedStyle(element);
  555. var padding = parseFloat(styles.paddingLeft) + parseFloat(styles.paddingRight);
  556. return element.clientWidth - padding;
  557. }
  558. function fire$1(target, type, properties) {
  559. var evt = document.createEvent("HTMLEvents");
  560. evt.initEvent(type, true, true);
  561. for (var j in properties) {
  562. evt[j] = properties[j];
  563. }
  564. return target.dispatchEvent(evt);
  565. }
  566. // https://css-tricks.com/snippets/javascript/loop-queryselectorall-matches/
  567. var BASE_MEASURES$1 = {
  568. margins: {
  569. top: 10,
  570. bottom: 10,
  571. left: 20,
  572. right: 20
  573. },
  574. paddings: {
  575. top: 20,
  576. bottom: 40,
  577. left: 30,
  578. right: 10
  579. },
  580. baseHeight: 240,
  581. titleHeight: 20,
  582. legendHeight: 30,
  583. titleFontSize: 12
  584. };
  585. function getTopOffset$1(m) {
  586. return m.titleHeight + m.margins.top + m.paddings.top;
  587. }
  588. function getLeftOffset$1(m) {
  589. return m.margins.left + m.paddings.left;
  590. }
  591. function getExtraHeight$1(m) {
  592. var totalExtraHeight = m.margins.top + m.margins.bottom + m.paddings.top + m.paddings.bottom + m.titleHeight + m.legendHeight;
  593. return totalExtraHeight;
  594. }
  595. function getExtraWidth$1(m) {
  596. var totalExtraWidth = m.margins.left + m.margins.right + m.paddings.left + m.paddings.right;
  597. return totalExtraWidth;
  598. }
  599. var INIT_CHART_UPDATE_TIMEOUT$1 = 700;
  600. var CHART_POST_ANIMATE_TIMEOUT$1 = 400;
  601. var AXIS_CHART_DEFAULT_TYPE$1 = 'line';
  602. var AXIS_DATASET_CHART_TYPES$1 = ['line', 'bar'];
  603. var AXIS_LEGEND_BAR_SIZE$1 = 100;
  604. var BAR_CHART_SPACE_RATIO$1 = 1;
  605. var MIN_BAR_PERCENT_HEIGHT$1 = 0.02;
  606. var LINE_CHART_DOT_SIZE$1 = 4;
  607. var DOT_OVERLAY_SIZE_INCR$1 = 4;
  608. var PERCENTAGE_BAR_DEFAULT_HEIGHT$1 = 20;
  609. var PERCENTAGE_BAR_DEFAULT_DEPTH$1 = 2;
  610. // Fixed 5-color theme,
  611. // More colors are difficult to parse visually
  612. var HEATMAP_DISTRIBUTION_SIZE$1 = 5;
  613. var HEATMAP_SQUARE_SIZE$1 = 10;
  614. var HEATMAP_GUTTER_SIZE$1 = 2;
  615. var DEFAULT_CHAR_WIDTH$1 = 7;
  616. var TOOLTIP_POINTER_TRIANGLE_HEIGHT$1 = 5;
  617. var DEFAULT_CHART_COLORS$1 = ['light-blue', 'blue', 'violet', 'red', 'orange', 'yellow', 'green', 'light-green', 'purple', 'magenta', 'light-grey', 'dark-grey'];
  618. var HEATMAP_COLORS_GREEN$1 = ['#ebedf0', '#c6e48b', '#7bc96f', '#239a3b', '#196127'];
  619. var DEFAULT_COLORS$1 = {
  620. bar: DEFAULT_CHART_COLORS$1,
  621. line: DEFAULT_CHART_COLORS$1,
  622. pie: DEFAULT_CHART_COLORS$1,
  623. percentage: DEFAULT_CHART_COLORS$1,
  624. heatmap: HEATMAP_COLORS_GREEN$1
  625. };
  626. // Universal constants
  627. var ANGLE_RATIO$1 = Math.PI / 180;
  628. var FULL_ANGLE$1 = 360;
  629. var _createClass$3 = function () {
  630. function defineProperties(target, props) {
  631. for (var i = 0; i < props.length; i++) {
  632. 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);
  633. }
  634. }return function (Constructor, protoProps, staticProps) {
  635. if (protoProps) defineProperties(Constructor.prototype, protoProps);if (staticProps) defineProperties(Constructor, staticProps);return Constructor;
  636. };
  637. }();
  638. function _classCallCheck$4(instance, Constructor) {
  639. if (!(instance instanceof Constructor)) {
  640. throw new TypeError("Cannot call a class as a function");
  641. }
  642. }
  643. var SvgTip = function () {
  644. function SvgTip(_ref) {
  645. var _ref$parent = _ref.parent,
  646. parent = _ref$parent === undefined ? null : _ref$parent,
  647. _ref$colors = _ref.colors,
  648. colors = _ref$colors === undefined ? [] : _ref$colors;
  649. _classCallCheck$4(this, SvgTip);
  650. this.parent = parent;
  651. this.colors = colors;
  652. this.titleName = '';
  653. this.titleValue = '';
  654. this.listValues = [];
  655. this.titleValueFirst = 0;
  656. this.x = 0;
  657. this.y = 0;
  658. this.top = 0;
  659. this.left = 0;
  660. this.setup();
  661. }
  662. _createClass$3(SvgTip, [{
  663. key: 'setup',
  664. value: function setup() {
  665. this.makeTooltip();
  666. }
  667. }, {
  668. key: 'refresh',
  669. value: function refresh() {
  670. this.fill();
  671. this.calcPosition();
  672. }
  673. }, {
  674. key: 'makeTooltip',
  675. value: function makeTooltip() {
  676. var _this = this;
  677. this.container = $$1.create('div', {
  678. inside: this.parent,
  679. className: 'graph-svg-tip comparison',
  680. 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>'
  681. });
  682. this.hideTip();
  683. this.title = this.container.querySelector('.title');
  684. this.dataPointList = this.container.querySelector('.data-point-list');
  685. this.parent.addEventListener('mouseleave', function () {
  686. _this.hideTip();
  687. });
  688. }
  689. }, {
  690. key: 'fill',
  691. value: function fill() {
  692. var _this2 = this;
  693. var title = void 0;
  694. if (this.index) {
  695. this.container.setAttribute('data-point-index', this.index);
  696. }
  697. if (this.titleValueFirst) {
  698. title = '<strong>' + this.titleValue + '</strong>' + this.titleName;
  699. } else {
  700. title = this.titleName + '<strong>' + this.titleValue + '</strong>';
  701. }
  702. this.title.innerHTML = title;
  703. this.dataPointList.innerHTML = '';
  704. this.listValues.map(function (set$$1, i) {
  705. var color = _this2.colors[i] || 'black';
  706. var value = set$$1.formatted === 0 || set$$1.formatted ? set$$1.formatted : set$$1.value;
  707. var li = $$1.create('li', {
  708. styles: {
  709. 'border-top': '3px solid ' + color
  710. },
  711. innerHTML: '<strong style="display: block;">' + (value === 0 || value ? value : '') + '</strong>\n\t\t\t\t\t' + (set$$1.title ? set$$1.title : '')
  712. });
  713. _this2.dataPointList.appendChild(li);
  714. });
  715. }
  716. }, {
  717. key: 'calcPosition',
  718. value: function calcPosition() {
  719. var width = this.container.offsetWidth;
  720. this.top = this.y - this.container.offsetHeight - TOOLTIP_POINTER_TRIANGLE_HEIGHT$1;
  721. this.left = this.x - width / 2;
  722. var maxLeft = this.parent.offsetWidth - width;
  723. var pointer = this.container.querySelector('.svg-pointer');
  724. if (this.left < 0) {
  725. pointer.style.left = 'calc(50% - ' + -1 * this.left + 'px)';
  726. this.left = 0;
  727. } else if (this.left > maxLeft) {
  728. var delta = this.left - maxLeft;
  729. var pointerOffset = 'calc(50% + ' + delta + 'px)';
  730. pointer.style.left = pointerOffset;
  731. this.left = maxLeft;
  732. } else {
  733. pointer.style.left = '50%';
  734. }
  735. }
  736. }, {
  737. key: 'setValues',
  738. value: function setValues(x, y) {
  739. var title = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
  740. var listValues = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : [];
  741. var index = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : -1;
  742. this.titleName = title.name;
  743. this.titleValue = title.value;
  744. this.listValues = listValues;
  745. this.x = x;
  746. this.y = y;
  747. this.titleValueFirst = title.valueFirst || 0;
  748. this.index = index;
  749. this.refresh();
  750. }
  751. }, {
  752. key: 'hideTip',
  753. value: function hideTip() {
  754. this.container.style.top = '0px';
  755. this.container.style.left = '0px';
  756. this.container.style.opacity = '0';
  757. }
  758. }, {
  759. key: 'showTip',
  760. value: function showTip() {
  761. this.container.style.top = this.top + 'px';
  762. this.container.style.left = this.left + 'px';
  763. this.container.style.opacity = '1';
  764. }
  765. }]);
  766. return SvgTip;
  767. }();
  768. /**
  769. * Returns the value of a number upto 2 decimal places.
  770. * @param {Number} d Any number
  771. */
  772. function floatTwo$1(d) {
  773. return parseFloat(d.toFixed(2));
  774. }
  775. /**
  776. * Returns whether or not two given arrays are equal.
  777. * @param {Array} arr1 First array
  778. * @param {Array} arr2 Second array
  779. */
  780. /**
  781. * Shuffles array in place. ES6 version
  782. * @param {Array} array An array containing the items.
  783. */
  784. /**
  785. * Fill an array with extra points
  786. * @param {Array} array Array
  787. * @param {Number} count number of filler elements
  788. * @param {Object} element element to fill with
  789. * @param {Boolean} start fill at start?
  790. */
  791. function fillArray$1(array, count, element) {
  792. var start = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false;
  793. if (!element) {
  794. element = start ? array[0] : array[array.length - 1];
  795. }
  796. var fillerArray = new Array(Math.abs(count)).fill(element);
  797. array = start ? fillerArray.concat(array) : array.concat(fillerArray);
  798. return array;
  799. }
  800. /**
  801. * Returns pixel width of string.
  802. * @param {String} string
  803. * @param {Number} charWidth Width of single char in pixels
  804. */
  805. function getStringWidth$1(string, charWidth) {
  806. return (string + "").length * charWidth;
  807. }
  808. // https://stackoverflow.com/a/29325222
  809. function getPositionByAngle$1(angle, radius) {
  810. return {
  811. x: Math.sin(angle * ANGLE_RATIO$1) * radius,
  812. y: Math.cos(angle * ANGLE_RATIO$1) * radius
  813. };
  814. }
  815. function getBarHeightAndYAttr(yTop, zeroLine) {
  816. var height = void 0,
  817. y = void 0;
  818. if (yTop <= zeroLine) {
  819. height = zeroLine - yTop;
  820. y = yTop;
  821. } else {
  822. height = yTop - zeroLine;
  823. y = zeroLine;
  824. }
  825. return [height, y];
  826. }
  827. function equilizeNoOfElements(array1, array2) {
  828. var extraCount = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : array2.length - array1.length;
  829. // Doesn't work if either has zero elements.
  830. if (extraCount > 0) {
  831. array1 = fillArray$1(array1, extraCount);
  832. } else {
  833. array2 = fillArray$1(array2, extraCount);
  834. }
  835. return [array1, array2];
  836. }
  837. var PRESET_COLOR_MAP = {
  838. 'light-blue': '#7cd6fd',
  839. 'blue': '#5e64ff',
  840. 'violet': '#743ee2',
  841. 'red': '#ff5858',
  842. 'orange': '#ffa00a',
  843. 'yellow': '#feef72',
  844. 'green': '#28a745',
  845. 'light-green': '#98d85b',
  846. 'purple': '#b554ff',
  847. 'magenta': '#ffa3ef',
  848. 'black': '#36114C',
  849. 'grey': '#bdd3e6',
  850. 'light-grey': '#f0f4f7',
  851. 'dark-grey': '#b8c2cc'
  852. };
  853. function limitColor(r) {
  854. if (r > 255) return 255;else if (r < 0) return 0;
  855. return r;
  856. }
  857. function lightenDarkenColor(color, amt) {
  858. var col = getColor(color);
  859. var usePound = false;
  860. if (col[0] == "#") {
  861. col = col.slice(1);
  862. usePound = true;
  863. }
  864. var num = parseInt(col, 16);
  865. var r = limitColor((num >> 16) + amt);
  866. var b = limitColor((num >> 8 & 0x00FF) + amt);
  867. var g = limitColor((num & 0x0000FF) + amt);
  868. return (usePound ? "#" : "") + (g | b << 8 | r << 16).toString(16);
  869. }
  870. function isValidColor(string) {
  871. // https://stackoverflow.com/a/8027444/6495043
  872. return (/(^#[0-9A-F]{6}$)|(^#[0-9A-F]{3}$)/i.test(string)
  873. );
  874. }
  875. var getColor = function getColor(color) {
  876. return PRESET_COLOR_MAP[color] || color;
  877. };
  878. var _slicedToArray = function () {
  879. function sliceIterator(arr, i) {
  880. var _arr = [];var _n = true;var _d = false;var _e = undefined;try {
  881. for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) {
  882. _arr.push(_s.value);if (i && _arr.length === i) break;
  883. }
  884. } catch (err) {
  885. _d = true;_e = err;
  886. } finally {
  887. try {
  888. if (!_n && _i["return"]) _i["return"]();
  889. } finally {
  890. if (_d) throw _e;
  891. }
  892. }return _arr;
  893. }return function (arr, i) {
  894. if (Array.isArray(arr)) {
  895. return arr;
  896. } else if (Symbol.iterator in Object(arr)) {
  897. return sliceIterator(arr, i);
  898. } else {
  899. throw new TypeError("Invalid attempt to destructure non-iterable instance");
  900. }
  901. };
  902. }();
  903. var _typeof$2$1 = typeof Symbol === "function" && _typeof2(Symbol.iterator) === "symbol" ? function (obj) {
  904. return typeof obj === 'undefined' ? 'undefined' : _typeof2(obj);
  905. } : function (obj) {
  906. return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj === 'undefined' ? 'undefined' : _typeof2(obj);
  907. };
  908. var AXIS_TICK_LENGTH = 6;
  909. var LABEL_MARGIN = 4;
  910. var FONT_SIZE = 10;
  911. var BASE_LINE_COLOR = '#dadada';
  912. var FONT_FILL = '#555b51';
  913. function $$1$1(expr, con) {
  914. return typeof expr === "string" ? (con || document).querySelector(expr) : expr || null;
  915. }
  916. function createSVG(tag, o) {
  917. var element = document.createElementNS("http://www.w3.org/2000/svg", tag);
  918. for (var i in o) {
  919. var val = o[i];
  920. if (i === "inside") {
  921. $$1$1(val).appendChild(element);
  922. } else if (i === "around") {
  923. var ref = $$1$1(val);
  924. ref.parentNode.insertBefore(element, ref);
  925. element.appendChild(ref);
  926. } else if (i === "styles") {
  927. if ((typeof val === 'undefined' ? 'undefined' : _typeof$2$1(val)) === "object") {
  928. Object.keys(val).map(function (prop) {
  929. element.style[prop] = val[prop];
  930. });
  931. }
  932. } else {
  933. if (i === "className") {
  934. i = "class";
  935. }
  936. if (i === "innerHTML") {
  937. element['textContent'] = val;
  938. } else {
  939. element.setAttribute(i, val);
  940. }
  941. }
  942. }
  943. return element;
  944. }
  945. function renderVerticalGradient(svgDefElem, gradientId) {
  946. return createSVG('linearGradient', {
  947. inside: svgDefElem,
  948. id: gradientId,
  949. x1: 0,
  950. x2: 0,
  951. y1: 0,
  952. y2: 1
  953. });
  954. }
  955. function setGradientStop(gradElem, offset, color, opacity) {
  956. return createSVG('stop', {
  957. 'inside': gradElem,
  958. 'style': 'stop-color: ' + color,
  959. 'offset': offset,
  960. 'stop-opacity': opacity
  961. });
  962. }
  963. function makeSVGContainer(parent, className, width, height) {
  964. return createSVG('svg', {
  965. className: className,
  966. inside: parent,
  967. width: width,
  968. height: height
  969. });
  970. }
  971. function makeSVGDefs(svgContainer) {
  972. return createSVG('defs', {
  973. inside: svgContainer
  974. });
  975. }
  976. function makeSVGGroup(className) {
  977. var transform = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '';
  978. var parent = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : undefined;
  979. var args = {
  980. className: className,
  981. transform: transform
  982. };
  983. if (parent) args.inside = parent;
  984. return createSVG('g', args);
  985. }
  986. function makePath(pathStr) {
  987. var className = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '';
  988. var stroke = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 'none';
  989. var fill = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 'none';
  990. return createSVG('path', {
  991. className: className,
  992. d: pathStr,
  993. styles: {
  994. stroke: stroke,
  995. fill: fill
  996. }
  997. });
  998. }
  999. function makeArcPathStr(startPosition, endPosition, center, radius) {
  1000. var clockWise = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : 1;
  1001. var arcStartX = center.x + startPosition.x,
  1002. arcStartY = center.y + startPosition.y;
  1003. var arcEndX = center.x + endPosition.x,
  1004. arcEndY = center.y + endPosition.y;
  1005. 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';
  1006. }
  1007. function makeGradient(svgDefElem, color) {
  1008. var lighter = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
  1009. var gradientId = 'path-fill-gradient' + '-' + color + '-' + (lighter ? 'lighter' : 'default');
  1010. var gradientDef = renderVerticalGradient(svgDefElem, gradientId);
  1011. var opacities = [1, 0.6, 0.2];
  1012. if (lighter) {
  1013. opacities = [0.4, 0.2, 0];
  1014. }
  1015. setGradientStop(gradientDef, "0%", color, opacities[0]);
  1016. setGradientStop(gradientDef, "50%", color, opacities[1]);
  1017. setGradientStop(gradientDef, "100%", color, opacities[2]);
  1018. return gradientId;
  1019. }
  1020. function percentageBar(x, y, width, height) {
  1021. var depth = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : PERCENTAGE_BAR_DEFAULT_DEPTH$1;
  1022. var fill = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : 'none';
  1023. var args = {
  1024. className: 'percentage-bar',
  1025. x: x,
  1026. y: y,
  1027. width: width,
  1028. height: height,
  1029. fill: fill,
  1030. styles: {
  1031. 'stroke': lightenDarkenColor(fill, -25),
  1032. // Diabolically good: https://stackoverflow.com/a/9000859
  1033. // https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/stroke-dasharray
  1034. 'stroke-dasharray': '0, ' + (height + width) + ', ' + width + ', ' + height,
  1035. 'stroke-width': depth
  1036. }
  1037. };
  1038. return createSVG("rect", args);
  1039. }
  1040. function heatSquare(className, x, y, size) {
  1041. var fill = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : 'none';
  1042. var data = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : {};
  1043. var args = {
  1044. className: className,
  1045. x: x,
  1046. y: y,
  1047. width: size,
  1048. height: size,
  1049. fill: fill
  1050. };
  1051. Object.keys(data).map(function (key) {
  1052. args[key] = data[key];
  1053. });
  1054. return createSVG("rect", args);
  1055. }
  1056. function legendBar(x, y, size) {
  1057. var fill = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 'none';
  1058. var label = arguments[4];
  1059. var args = {
  1060. className: 'legend-bar',
  1061. x: 0,
  1062. y: 0,
  1063. width: size,
  1064. height: '2px',
  1065. fill: fill
  1066. };
  1067. var text = createSVG('text', {
  1068. className: 'legend-dataset-text',
  1069. x: 0,
  1070. y: 0,
  1071. dy: FONT_SIZE * 2 + 'px',
  1072. 'font-size': FONT_SIZE * 1.2 + 'px',
  1073. 'text-anchor': 'start',
  1074. fill: FONT_FILL,
  1075. innerHTML: label
  1076. });
  1077. var group = createSVG('g', {
  1078. transform: 'translate(' + x + ', ' + y + ')'
  1079. });
  1080. group.appendChild(createSVG("rect", args));
  1081. group.appendChild(text);
  1082. return group;
  1083. }
  1084. function legendDot(x, y, size) {
  1085. var fill = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 'none';
  1086. var label = arguments[4];
  1087. var args = {
  1088. className: 'legend-dot',
  1089. cx: 0,
  1090. cy: 0,
  1091. r: size,
  1092. fill: fill
  1093. };
  1094. var text = createSVG('text', {
  1095. className: 'legend-dataset-text',
  1096. x: 0,
  1097. y: 0,
  1098. dx: FONT_SIZE + 'px',
  1099. dy: FONT_SIZE / 3 + 'px',
  1100. 'font-size': FONT_SIZE * 1.2 + 'px',
  1101. 'text-anchor': 'start',
  1102. fill: FONT_FILL,
  1103. innerHTML: label
  1104. });
  1105. var group = createSVG('g', {
  1106. transform: 'translate(' + x + ', ' + y + ')'
  1107. });
  1108. group.appendChild(createSVG("circle", args));
  1109. group.appendChild(text);
  1110. return group;
  1111. }
  1112. function makeText(className, x, y, content) {
  1113. var options = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : {};
  1114. var fontSize = options.fontSize || FONT_SIZE;
  1115. var dy = options.dy !== undefined ? options.dy : fontSize / 2;
  1116. var fill = options.fill || FONT_FILL;
  1117. var textAnchor = options.textAnchor || 'start';
  1118. return createSVG('text', {
  1119. className: className,
  1120. x: x,
  1121. y: y,
  1122. dy: dy + 'px',
  1123. 'font-size': fontSize + 'px',
  1124. fill: fill,
  1125. 'text-anchor': textAnchor,
  1126. innerHTML: content
  1127. });
  1128. }
  1129. function makeVertLine(x, label, y1, y2) {
  1130. var options = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : {};
  1131. if (!options.stroke) options.stroke = BASE_LINE_COLOR;
  1132. var l = createSVG('line', {
  1133. className: 'line-vertical ' + options.className,
  1134. x1: 0,
  1135. x2: 0,
  1136. y1: y1,
  1137. y2: y2,
  1138. styles: {
  1139. stroke: options.stroke
  1140. }
  1141. });
  1142. var text = createSVG('text', {
  1143. x: 0,
  1144. y: y1 > y2 ? y1 + LABEL_MARGIN : y1 - LABEL_MARGIN - FONT_SIZE,
  1145. dy: FONT_SIZE + 'px',
  1146. 'font-size': FONT_SIZE + 'px',
  1147. 'text-anchor': 'middle',
  1148. innerHTML: label + ""
  1149. });
  1150. var line = createSVG('g', {
  1151. transform: 'translate(' + x + ', 0)'
  1152. });
  1153. line.appendChild(l);
  1154. line.appendChild(text);
  1155. return line;
  1156. }
  1157. function makeHoriLine(y, label, x1, x2) {
  1158. var options = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : {};
  1159. if (!options.stroke) options.stroke = BASE_LINE_COLOR;
  1160. if (!options.lineType) options.lineType = '';
  1161. var className = 'line-horizontal ' + options.className + (options.lineType === "dashed" ? "dashed" : "");
  1162. var l = createSVG('line', {
  1163. className: className,
  1164. x1: x1,
  1165. x2: x2,
  1166. y1: 0,
  1167. y2: 0,
  1168. styles: {
  1169. stroke: options.stroke
  1170. }
  1171. });
  1172. var text = createSVG('text', {
  1173. x: x1 < x2 ? x1 - LABEL_MARGIN : x1 + LABEL_MARGIN,
  1174. y: 0,
  1175. dy: FONT_SIZE / 2 - 2 + 'px',
  1176. 'font-size': FONT_SIZE + 'px',
  1177. 'text-anchor': x1 < x2 ? 'end' : 'start',
  1178. innerHTML: label + ""
  1179. });
  1180. var line = createSVG('g', {
  1181. transform: 'translate(0, ' + y + ')',
  1182. 'stroke-opacity': 1
  1183. });
  1184. if (text === 0 || text === '0') {
  1185. line.style.stroke = "rgba(27, 31, 35, 0.6)";
  1186. }
  1187. line.appendChild(l);
  1188. line.appendChild(text);
  1189. return line;
  1190. }
  1191. function yLine(y, label, width) {
  1192. var options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
  1193. if (!options.pos) options.pos = 'left';
  1194. if (!options.offset) options.offset = 0;
  1195. if (!options.mode) options.mode = 'span';
  1196. if (!options.stroke) options.stroke = BASE_LINE_COLOR;
  1197. if (!options.className) options.className = '';
  1198. var x1 = -1 * AXIS_TICK_LENGTH;
  1199. var x2 = options.mode === 'span' ? width + AXIS_TICK_LENGTH : 0;
  1200. if (options.mode === 'tick' && options.pos === 'right') {
  1201. x1 = width + AXIS_TICK_LENGTH;
  1202. x2 = width;
  1203. }
  1204. // let offset = options.pos === 'left' ? -1 * options.offset : options.offset;
  1205. x1 += options.offset;
  1206. x2 += options.offset;
  1207. return makeHoriLine(y, label, x1, x2, {
  1208. stroke: options.stroke,
  1209. className: options.className,
  1210. lineType: options.lineType
  1211. });
  1212. }
  1213. function xLine(x, label, height) {
  1214. var options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
  1215. if (!options.pos) options.pos = 'bottom';
  1216. if (!options.offset) options.offset = 0;
  1217. if (!options.mode) options.mode = 'span';
  1218. if (!options.stroke) options.stroke = BASE_LINE_COLOR;
  1219. if (!options.className) options.className = '';
  1220. // Draw X axis line in span/tick mode with optional label
  1221. // y2(span)
  1222. // |
  1223. // |
  1224. // x line |
  1225. // |
  1226. // |
  1227. // ---------------------+-- y2(tick)
  1228. // |
  1229. // y1
  1230. var y1 = height + AXIS_TICK_LENGTH;
  1231. var y2 = options.mode === 'span' ? -1 * AXIS_TICK_LENGTH : height;
  1232. if (options.mode === 'tick' && options.pos === 'top') {
  1233. // top axis ticks
  1234. y1 = -1 * AXIS_TICK_LENGTH;
  1235. y2 = 0;
  1236. }
  1237. return makeVertLine(x, label, y1, y2, {
  1238. stroke: options.stroke,
  1239. className: options.className,
  1240. lineType: options.lineType
  1241. });
  1242. }
  1243. function yMarker(y, label, width) {
  1244. var options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
  1245. if (!options.labelPos) options.labelPos = 'right';
  1246. var x = options.labelPos === 'left' ? LABEL_MARGIN : width - getStringWidth$1(label, 5) - LABEL_MARGIN;
  1247. var labelSvg = createSVG('text', {
  1248. className: 'chart-label',
  1249. x: x,
  1250. y: 0,
  1251. dy: FONT_SIZE / -2 + 'px',
  1252. 'font-size': FONT_SIZE + 'px',
  1253. 'text-anchor': 'start',
  1254. innerHTML: label + ""
  1255. });
  1256. var line = makeHoriLine(y, '', 0, width, {
  1257. stroke: options.stroke || BASE_LINE_COLOR,
  1258. className: options.className || '',
  1259. lineType: options.lineType
  1260. });
  1261. line.appendChild(labelSvg);
  1262. return line;
  1263. }
  1264. function yRegion(y1, y2, width, label) {
  1265. var options = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : {};
  1266. // return a group
  1267. var height = y1 - y2;
  1268. var rect = createSVG('rect', {
  1269. className: 'bar mini', // remove class
  1270. styles: {
  1271. fill: 'rgba(228, 234, 239, 0.49)',
  1272. stroke: BASE_LINE_COLOR,
  1273. 'stroke-dasharray': width + ', ' + height
  1274. },
  1275. // 'data-point-index': index,
  1276. x: 0,
  1277. y: 0,
  1278. width: width,
  1279. height: height
  1280. });
  1281. if (!options.labelPos) options.labelPos = 'right';
  1282. var x = options.labelPos === 'left' ? LABEL_MARGIN : width - getStringWidth$1(label + "", 4.5) - LABEL_MARGIN;
  1283. var labelSvg = createSVG('text', {
  1284. className: 'chart-label',
  1285. x: x,
  1286. y: 0,
  1287. dy: FONT_SIZE / -2 + 'px',
  1288. 'font-size': FONT_SIZE + 'px',
  1289. 'text-anchor': 'start',
  1290. innerHTML: label + ""
  1291. });
  1292. var region = createSVG('g', {
  1293. transform: 'translate(0, ' + y2 + ')'
  1294. });
  1295. region.appendChild(rect);
  1296. region.appendChild(labelSvg);
  1297. return region;
  1298. }
  1299. function datasetBar(x, yTop, width, color) {
  1300. var label = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : '';
  1301. var index = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : 0;
  1302. var offset = arguments.length > 6 && arguments[6] !== undefined ? arguments[6] : 0;
  1303. var meta = arguments.length > 7 && arguments[7] !== undefined ? arguments[7] : {};
  1304. var _getBarHeightAndYAttr = getBarHeightAndYAttr(yTop, meta.zeroLine),
  1305. _getBarHeightAndYAttr2 = _slicedToArray(_getBarHeightAndYAttr, 2),
  1306. height = _getBarHeightAndYAttr2[0],
  1307. y = _getBarHeightAndYAttr2[1];
  1308. y -= offset;
  1309. if (height === 0) {
  1310. height = meta.minHeight;
  1311. y -= meta.minHeight;
  1312. }
  1313. var rect = createSVG('rect', {
  1314. className: 'bar mini',
  1315. style: 'fill: ' + color,
  1316. 'data-point-index': index,
  1317. x: x,
  1318. y: y,
  1319. width: width,
  1320. height: height
  1321. });
  1322. label += "";
  1323. if (!label && !label.length) {
  1324. return rect;
  1325. } else {
  1326. rect.setAttribute('y', 0);
  1327. rect.setAttribute('x', 0);
  1328. var text = createSVG('text', {
  1329. className: 'data-point-value',
  1330. x: width / 2,
  1331. y: 0,
  1332. dy: FONT_SIZE / 2 * -1 + 'px',
  1333. 'font-size': FONT_SIZE + 'px',
  1334. 'text-anchor': 'middle',
  1335. innerHTML: label
  1336. });
  1337. var group = createSVG('g', {
  1338. 'data-point-index': index,
  1339. transform: 'translate(' + x + ', ' + y + ')'
  1340. });
  1341. group.appendChild(rect);
  1342. group.appendChild(text);
  1343. return group;
  1344. }
  1345. }
  1346. function datasetDot(x, y, radius, color) {
  1347. var label = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : '';
  1348. var index = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : 0;
  1349. var dot = createSVG('circle', {
  1350. style: 'fill: ' + color,
  1351. 'data-point-index': index,
  1352. cx: x,
  1353. cy: y,
  1354. r: radius
  1355. });
  1356. label += "";
  1357. if (!label && !label.length) {
  1358. return dot;
  1359. } else {
  1360. dot.setAttribute('cy', 0);
  1361. dot.setAttribute('cx', 0);
  1362. var text = createSVG('text', {
  1363. className: 'data-point-value',
  1364. x: 0,
  1365. y: 0,
  1366. dy: FONT_SIZE / 2 * -1 - radius + 'px',
  1367. 'font-size': FONT_SIZE + 'px',
  1368. 'text-anchor': 'middle',
  1369. innerHTML: label
  1370. });
  1371. var group = createSVG('g', {
  1372. 'data-point-index': index,
  1373. transform: 'translate(' + x + ', ' + y + ')'
  1374. });
  1375. group.appendChild(dot);
  1376. group.appendChild(text);
  1377. return group;
  1378. }
  1379. }
  1380. function getPaths(xList, yList, color) {
  1381. var options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
  1382. var meta = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : {};
  1383. var pointsList = yList.map(function (y, i) {
  1384. return xList[i] + ',' + y;
  1385. });
  1386. var pointsStr = pointsList.join("L");
  1387. var path = makePath("M" + pointsStr, 'line-graph-path', color);
  1388. // HeatLine
  1389. if (options.heatline) {
  1390. var gradient_id = makeGradient(meta.svgDefs, color);
  1391. path.style.stroke = 'url(#' + gradient_id + ')';
  1392. }
  1393. var paths = {
  1394. path: path
  1395. };
  1396. // Region
  1397. if (options.areaFill) {
  1398. var gradient_id_region = makeGradient(meta.svgDefs, color, true);
  1399. var pathStr = "M" + (xList[0] + ',' + meta.zeroLine + 'L') + pointsStr + ('L' + xList.slice(-1)[0] + ',' + meta.zeroLine);
  1400. paths.region = makePath(pathStr, 'region-fill', 'none', 'url(#' + gradient_id_region + ')');
  1401. }
  1402. return paths;
  1403. }
  1404. var makeOverlay = {
  1405. 'bar': function bar(unit) {
  1406. var transformValue = void 0;
  1407. if (unit.nodeName !== 'rect') {
  1408. transformValue = unit.getAttribute('transform');
  1409. unit = unit.childNodes[0];
  1410. }
  1411. var overlay = unit.cloneNode();
  1412. overlay.style.fill = '#000000';
  1413. overlay.style.opacity = '0.4';
  1414. if (transformValue) {
  1415. overlay.setAttribute('transform', transformValue);
  1416. }
  1417. return overlay;
  1418. },
  1419. 'dot': function dot(unit) {
  1420. var transformValue = void 0;
  1421. if (unit.nodeName !== 'circle') {
  1422. transformValue = unit.getAttribute('transform');
  1423. unit = unit.childNodes[0];
  1424. }
  1425. var overlay = unit.cloneNode();
  1426. var radius = unit.getAttribute('r');
  1427. var fill = unit.getAttribute('fill');
  1428. overlay.setAttribute('r', parseInt(radius) + DOT_OVERLAY_SIZE_INCR$1);
  1429. overlay.setAttribute('fill', fill);
  1430. overlay.style.opacity = '0.6';
  1431. if (transformValue) {
  1432. overlay.setAttribute('transform', transformValue);
  1433. }
  1434. return overlay;
  1435. },
  1436. 'heat_square': function heat_square(unit) {
  1437. var transformValue = void 0;
  1438. if (unit.nodeName !== 'circle') {
  1439. transformValue = unit.getAttribute('transform');
  1440. unit = unit.childNodes[0];
  1441. }
  1442. var overlay = unit.cloneNode();
  1443. var radius = unit.getAttribute('r');
  1444. var fill = unit.getAttribute('fill');
  1445. overlay.setAttribute('r', parseInt(radius) + DOT_OVERLAY_SIZE_INCR$1);
  1446. overlay.setAttribute('fill', fill);
  1447. overlay.style.opacity = '0.6';
  1448. if (transformValue) {
  1449. overlay.setAttribute('transform', transformValue);
  1450. }
  1451. return overlay;
  1452. }
  1453. };
  1454. var updateOverlay = {
  1455. 'bar': function bar(unit, overlay) {
  1456. var transformValue = void 0;
  1457. if (unit.nodeName !== 'rect') {
  1458. transformValue = unit.getAttribute('transform');
  1459. unit = unit.childNodes[0];
  1460. }
  1461. var attributes = ['x', 'y', 'width', 'height'];
  1462. Object.values(unit.attributes).filter(function (attr) {
  1463. return attributes.includes(attr.name) && attr.specified;
  1464. }).map(function (attr) {
  1465. overlay.setAttribute(attr.name, attr.nodeValue);
  1466. });
  1467. if (transformValue) {
  1468. overlay.setAttribute('transform', transformValue);
  1469. }
  1470. },
  1471. 'dot': function dot(unit, overlay) {
  1472. var transformValue = void 0;
  1473. if (unit.nodeName !== 'circle') {
  1474. transformValue = unit.getAttribute('transform');
  1475. unit = unit.childNodes[0];
  1476. }
  1477. var attributes = ['cx', 'cy'];
  1478. Object.values(unit.attributes).filter(function (attr) {
  1479. return attributes.includes(attr.name) && attr.specified;
  1480. }).map(function (attr) {
  1481. overlay.setAttribute(attr.name, attr.nodeValue);
  1482. });
  1483. if (transformValue) {
  1484. overlay.setAttribute('transform', transformValue);
  1485. }
  1486. },
  1487. 'heat_square': function heat_square(unit, overlay) {
  1488. var transformValue = void 0;
  1489. if (unit.nodeName !== 'circle') {
  1490. transformValue = unit.getAttribute('transform');
  1491. unit = unit.childNodes[0];
  1492. }
  1493. var attributes = ['cx', 'cy'];
  1494. Object.values(unit.attributes).filter(function (attr) {
  1495. return attributes.includes(attr.name) && attr.specified;
  1496. }).map(function (attr) {
  1497. overlay.setAttribute(attr.name, attr.nodeValue);
  1498. });
  1499. if (transformValue) {
  1500. overlay.setAttribute('transform', transformValue);
  1501. }
  1502. }
  1503. };
  1504. var _slicedToArray$2 = function () {
  1505. function sliceIterator(arr, i) {
  1506. var _arr = [];var _n = true;var _d = false;var _e = undefined;try {
  1507. for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) {
  1508. _arr.push(_s.value);if (i && _arr.length === i) break;
  1509. }
  1510. } catch (err) {
  1511. _d = true;_e = err;
  1512. } finally {
  1513. try {
  1514. if (!_n && _i["return"]) _i["return"]();
  1515. } finally {
  1516. if (_d) throw _e;
  1517. }
  1518. }return _arr;
  1519. }return function (arr, i) {
  1520. if (Array.isArray(arr)) {
  1521. return arr;
  1522. } else if (Symbol.iterator in Object(arr)) {
  1523. return sliceIterator(arr, i);
  1524. } else {
  1525. throw new TypeError("Invalid attempt to destructure non-iterable instance");
  1526. }
  1527. };
  1528. }();
  1529. var UNIT_ANIM_DUR = 350;
  1530. var PATH_ANIM_DUR = 350;
  1531. var MARKER_LINE_ANIM_DUR = UNIT_ANIM_DUR;
  1532. var REPLACE_ALL_NEW_DUR = 250;
  1533. var STD_EASING = 'easein';
  1534. function translate(unit, oldCoord, newCoord, duration) {
  1535. var old = typeof oldCoord === 'string' ? oldCoord : oldCoord.join(', ');
  1536. return [unit, { transform: newCoord.join(', ') }, duration, STD_EASING, "translate", { transform: old }];
  1537. }
  1538. function translateVertLine(xLine, newX, oldX) {
  1539. return translate(xLine, [oldX, 0], [newX, 0], MARKER_LINE_ANIM_DUR);
  1540. }
  1541. function translateHoriLine(yLine, newY, oldY) {
  1542. return translate(yLine, [0, oldY], [0, newY], MARKER_LINE_ANIM_DUR);
  1543. }
  1544. function animateRegion(rectGroup, newY1, newY2, oldY2) {
  1545. var newHeight = newY1 - newY2;
  1546. var rect = rectGroup.childNodes[0];
  1547. var width = rect.getAttribute("width");
  1548. var rectAnim = [rect, { height: newHeight, 'stroke-dasharray': width + ', ' + newHeight }, MARKER_LINE_ANIM_DUR, STD_EASING];
  1549. var groupAnim = translate(rectGroup, [0, oldY2], [0, newY2], MARKER_LINE_ANIM_DUR);
  1550. return [rectAnim, groupAnim];
  1551. }
  1552. function animateBar(bar, x, yTop, width) {
  1553. var offset = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : 0;
  1554. var meta = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : {};
  1555. var _getBarHeightAndYAttr = getBarHeightAndYAttr(yTop, meta.zeroLine),
  1556. _getBarHeightAndYAttr2 = _slicedToArray$2(_getBarHeightAndYAttr, 2),
  1557. height = _getBarHeightAndYAttr2[0],
  1558. y = _getBarHeightAndYAttr2[1];
  1559. y -= offset;
  1560. if (bar.nodeName !== 'rect') {
  1561. var rect = bar.childNodes[0];
  1562. var rectAnim = [rect, { width: width, height: height }, UNIT_ANIM_DUR, STD_EASING];
  1563. var oldCoordStr = bar.getAttribute("transform").split("(")[1].slice(0, -1);
  1564. var groupAnim = translate(bar, oldCoordStr, [x, y], MARKER_LINE_ANIM_DUR);
  1565. return [rectAnim, groupAnim];
  1566. } else {
  1567. return [[bar, { width: width, height: height, x: x, y: y }, UNIT_ANIM_DUR, STD_EASING]];
  1568. }
  1569. // bar.animate({height: args.newHeight, y: yTop}, UNIT_ANIM_DUR, mina.easein);
  1570. }
  1571. function animateDot(dot, x, y) {
  1572. if (dot.nodeName !== 'circle') {
  1573. var oldCoordStr = dot.getAttribute("transform").split("(")[1].slice(0, -1);
  1574. var groupAnim = translate(dot, oldCoordStr, [x, y], MARKER_LINE_ANIM_DUR);
  1575. return [groupAnim];
  1576. } else {
  1577. return [[dot, { cx: x, cy: y }, UNIT_ANIM_DUR, STD_EASING]];
  1578. }
  1579. // dot.animate({cy: yTop}, UNIT_ANIM_DUR, mina.easein);
  1580. }
  1581. function animatePath(paths, newXList, newYList, zeroLine) {
  1582. var pathComponents = [];
  1583. var pointsStr = newYList.map(function (y, i) {
  1584. return newXList[i] + ',' + y;
  1585. });
  1586. var pathStr = pointsStr.join("L");
  1587. var animPath = [paths.path, { d: "M" + pathStr }, PATH_ANIM_DUR, STD_EASING];
  1588. pathComponents.push(animPath);
  1589. if (paths.region) {
  1590. var regStartPt = newXList[0] + ',' + zeroLine + 'L';
  1591. var regEndPt = 'L' + newXList.slice(-1)[0] + ', ' + zeroLine;
  1592. var animRegion = [paths.region, { d: "M" + regStartPt + pathStr + regEndPt }, PATH_ANIM_DUR, STD_EASING];
  1593. pathComponents.push(animRegion);
  1594. }
  1595. return pathComponents;
  1596. }
  1597. function animatePathStr(oldPath, pathStr) {
  1598. return [oldPath, { d: pathStr }, UNIT_ANIM_DUR, STD_EASING];
  1599. }
  1600. var _slicedToArray$1 = function () {
  1601. function sliceIterator(arr, i) {
  1602. var _arr = [];var _n = true;var _d = false;var _e = undefined;try {
  1603. for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) {
  1604. _arr.push(_s.value);if (i && _arr.length === i) break;
  1605. }
  1606. } catch (err) {
  1607. _d = true;_e = err;
  1608. } finally {
  1609. try {
  1610. if (!_n && _i["return"]) _i["return"]();
  1611. } finally {
  1612. if (_d) throw _e;
  1613. }
  1614. }return _arr;
  1615. }return function (arr, i) {
  1616. if (Array.isArray(arr)) {
  1617. return arr;
  1618. } else if (Symbol.iterator in Object(arr)) {
  1619. return sliceIterator(arr, i);
  1620. } else {
  1621. throw new TypeError("Invalid attempt to destructure non-iterable instance");
  1622. }
  1623. };
  1624. }();
  1625. function _toConsumableArray$1(arr) {
  1626. if (Array.isArray(arr)) {
  1627. for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) {
  1628. arr2[i] = arr[i];
  1629. }return arr2;
  1630. } else {
  1631. return Array.from(arr);
  1632. }
  1633. }
  1634. // Leveraging SMIL Animations
  1635. var EASING = {
  1636. ease: "0.25 0.1 0.25 1",
  1637. linear: "0 0 1 1",
  1638. // easein: "0.42 0 1 1",
  1639. easein: "0.1 0.8 0.2 1",
  1640. easeout: "0 0 0.58 1",
  1641. easeinout: "0.42 0 0.58 1"
  1642. };
  1643. function animateSVGElement(element, props, dur) {
  1644. var easingType = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : "linear";
  1645. var type = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : undefined;
  1646. var oldValues = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : {};
  1647. var animElement = element.cloneNode(true);
  1648. var newElement = element.cloneNode(true);
  1649. for (var attributeName in props) {
  1650. var animateElement = void 0;
  1651. if (attributeName === 'transform') {
  1652. animateElement = document.createElementNS("http://www.w3.org/2000/svg", "animateTransform");
  1653. } else {
  1654. animateElement = document.createElementNS("http://www.w3.org/2000/svg", "animate");
  1655. }
  1656. var currentValue = oldValues[attributeName] || element.getAttribute(attributeName);
  1657. var value = props[attributeName];
  1658. var animAttr = {
  1659. attributeName: attributeName,
  1660. from: currentValue,
  1661. to: value,
  1662. begin: "0s",
  1663. dur: dur / 1000 + "s",
  1664. values: currentValue + ";" + value,
  1665. keySplines: EASING[easingType],
  1666. keyTimes: "0;1",
  1667. calcMode: "spline",
  1668. fill: 'freeze'
  1669. };
  1670. if (type) {
  1671. animAttr["type"] = type;
  1672. }
  1673. for (var i in animAttr) {
  1674. animateElement.setAttribute(i, animAttr[i]);
  1675. }
  1676. animElement.appendChild(animateElement);
  1677. if (type) {
  1678. newElement.setAttribute(attributeName, "translate(" + value + ")");
  1679. } else {
  1680. newElement.setAttribute(attributeName, value);
  1681. }
  1682. }
  1683. return [animElement, newElement];
  1684. }
  1685. function transform(element, style) {
  1686. // eslint-disable-line no-unused-vars
  1687. element.style.transform = style;
  1688. element.style.webkitTransform = style;
  1689. element.style.msTransform = style;
  1690. element.style.mozTransform = style;
  1691. element.style.oTransform = style;
  1692. }
  1693. function animateSVG(svgContainer, elements) {
  1694. var newElements = [];
  1695. var animElements = [];
  1696. elements.map(function (element) {
  1697. var unit = element[0];
  1698. var parent = unit.parentNode;
  1699. var animElement = void 0,
  1700. newElement = void 0;
  1701. element[0] = unit;
  1702. var _animateSVGElement = animateSVGElement.apply(undefined, _toConsumableArray$1(element));
  1703. var _animateSVGElement2 = _slicedToArray$1(_animateSVGElement, 2);
  1704. animElement = _animateSVGElement2[0];
  1705. newElement = _animateSVGElement2[1];
  1706. newElements.push(newElement);
  1707. animElements.push([animElement, parent]);
  1708. parent.replaceChild(animElement, unit);
  1709. });
  1710. var animSvg = svgContainer.cloneNode(true);
  1711. animElements.map(function (animElement, i) {
  1712. animElement[1].replaceChild(newElements[i], animElement[0]);
  1713. elements[i][0] = newElements[i];
  1714. });
  1715. return animSvg;
  1716. }
  1717. function runSMILAnimation(parent, svgElement, elementsToAnimate) {
  1718. if (elementsToAnimate.length === 0) return;
  1719. var animSvgElement = animateSVG(svgElement, elementsToAnimate);
  1720. if (svgElement.parentNode == parent) {
  1721. parent.removeChild(svgElement);
  1722. parent.appendChild(animSvgElement);
  1723. }
  1724. // Replace the new svgElement (data has already been replaced)
  1725. setTimeout(function () {
  1726. if (animSvgElement.parentNode == parent) {
  1727. parent.removeChild(animSvgElement);
  1728. parent.appendChild(svgElement);
  1729. }
  1730. }, REPLACE_ALL_NEW_DUR);
  1731. }
  1732. 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}";
  1733. function downloadFile(filename, data) {
  1734. var a = document.createElement('a');
  1735. a.style = "display: none";
  1736. var blob = new Blob(data, { type: "image/svg+xml; charset=utf-8" });
  1737. var url = window.URL.createObjectURL(blob);
  1738. a.href = url;
  1739. a.download = filename;
  1740. document.body.appendChild(a);
  1741. a.click();
  1742. setTimeout(function () {
  1743. document.body.removeChild(a);
  1744. window.URL.revokeObjectURL(url);
  1745. }, 300);
  1746. }
  1747. function prepareForExport(svg) {
  1748. var clone = svg.cloneNode(true);
  1749. clone.classList.add('chart-container');
  1750. clone.setAttribute('xmlns', "http://www.w3.org/2000/svg");
  1751. clone.setAttribute('xmlns:xlink', "http://www.w3.org/1999/xlink");
  1752. var styleEl = $$1.create('style', {
  1753. 'innerHTML': CSSTEXT
  1754. });
  1755. clone.insertBefore(styleEl, clone.firstChild);
  1756. var container = $$1.create('div');
  1757. container.appendChild(clone);
  1758. return container.innerHTML;
  1759. }
  1760. var _createClass$2 = function () {
  1761. function defineProperties(target, props) {
  1762. for (var i = 0; i < props.length; i++) {
  1763. 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);
  1764. }
  1765. }return function (Constructor, protoProps, staticProps) {
  1766. if (protoProps) defineProperties(Constructor.prototype, protoProps);if (staticProps) defineProperties(Constructor, staticProps);return Constructor;
  1767. };
  1768. }();
  1769. function _classCallCheck$3(instance, Constructor) {
  1770. if (!(instance instanceof Constructor)) {
  1771. throw new TypeError("Cannot call a class as a function");
  1772. }
  1773. }
  1774. var BOUND_DRAW_FN = void 0;
  1775. var BaseChart = function () {
  1776. function BaseChart(parent, options) {
  1777. _classCallCheck$3(this, BaseChart);
  1778. this.parent = typeof parent === 'string' ? document.querySelector(parent) : parent;
  1779. if (!(this.parent instanceof HTMLElement)) {
  1780. throw new Error('No `parent` element to render on was provided.');
  1781. }
  1782. this.rawChartArgs = options;
  1783. this.title = options.title || '';
  1784. this.type = options.type || 'line';
  1785. this.realData = this.prepareData(options.data);
  1786. this.data = this.prepareFirstData(this.realData);
  1787. this.colors = this.validateColors(options.colors, this.type);
  1788. this.config = {
  1789. showTooltip: 1, // calculate
  1790. showLegend: 1, // calculate
  1791. isNavigable: options.isNavigable || 0,
  1792. animate: 1
  1793. };
  1794. this.measures = JSON.parse(JSON.stringify(BASE_MEASURES$1));
  1795. var m = this.measures;
  1796. this.setMeasures(options);
  1797. if (!this.title.length) {
  1798. m.titleHeight = 0;
  1799. }
  1800. if (!this.config.showLegend) m.legendHeight = 0;
  1801. this.argHeight = options.height || m.baseHeight;
  1802. this.state = {};
  1803. this.options = {};
  1804. this.initTimeout = INIT_CHART_UPDATE_TIMEOUT$1;
  1805. if (this.config.isNavigable) {
  1806. this.overlays = [];
  1807. }
  1808. this.configure(options);
  1809. }
  1810. _createClass$2(BaseChart, [{
  1811. key: 'prepareData',
  1812. value: function prepareData(data) {
  1813. return data;
  1814. }
  1815. }, {
  1816. key: 'prepareFirstData',
  1817. value: function prepareFirstData(data) {
  1818. return data;
  1819. }
  1820. }, {
  1821. key: 'validateColors',
  1822. value: function validateColors(colors, type) {
  1823. var validColors = [];
  1824. colors = (colors || []).concat(DEFAULT_COLORS$1[type]);
  1825. colors.forEach(function (string) {
  1826. var color = getColor(string);
  1827. if (!isValidColor(color)) {
  1828. console.warn('"' + string + '" is not a valid color.');
  1829. } else {
  1830. validColors.push(color);
  1831. }
  1832. });
  1833. return validColors;
  1834. }
  1835. }, {
  1836. key: 'setMeasures',
  1837. value: function setMeasures() {
  1838. // Override measures, including those for title and legend
  1839. // set config for legend and title
  1840. }
  1841. }, {
  1842. key: 'configure',
  1843. value: function configure() {
  1844. var height = this.argHeight;
  1845. this.baseHeight = height;
  1846. this.height = height - getExtraHeight$1(this.measures);
  1847. // Bind window events
  1848. BOUND_DRAW_FN = this.boundDrawFn.bind(this);
  1849. window.addEventListener('resize', BOUND_DRAW_FN);
  1850. window.addEventListener('orientationchange', this.boundDrawFn.bind(this));
  1851. }
  1852. }, {
  1853. key: 'boundDrawFn',
  1854. value: function boundDrawFn() {
  1855. this.draw(true);
  1856. }
  1857. }, {
  1858. key: 'unbindWindowEvents',
  1859. value: function unbindWindowEvents() {
  1860. window.removeEventListener('resize', BOUND_DRAW_FN);
  1861. window.removeEventListener('orientationchange', this.boundDrawFn.bind(this));
  1862. }
  1863. // Has to be called manually
  1864. }, {
  1865. key: 'setup',
  1866. value: function setup() {
  1867. this.makeContainer();
  1868. this.updateWidth();
  1869. this.makeTooltip();
  1870. this.draw(false, true);
  1871. }
  1872. }, {
  1873. key: 'makeContainer',
  1874. value: function makeContainer() {
  1875. // Chart needs a dedicated parent element
  1876. this.parent.innerHTML = '';
  1877. var args = {
  1878. inside: this.parent,
  1879. className: 'chart-container'
  1880. };
  1881. if (this.independentWidth) {
  1882. args.styles = { width: this.independentWidth + 'px' };
  1883. this.parent.style.overflow = 'auto';
  1884. }
  1885. this.container = $$1.create('div', args);
  1886. }
  1887. }, {
  1888. key: 'makeTooltip',
  1889. value: function makeTooltip() {
  1890. this.tip = new SvgTip({
  1891. parent: this.container,
  1892. colors: this.colors
  1893. });
  1894. this.bindTooltip();
  1895. }
  1896. }, {
  1897. key: 'bindTooltip',
  1898. value: function bindTooltip() {}
  1899. }, {
  1900. key: 'draw',
  1901. value: function draw() {
  1902. var _this = this;
  1903. var onlyWidthChange = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;
  1904. var init = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
  1905. this.updateWidth();
  1906. this.calc(onlyWidthChange);
  1907. this.makeChartArea();
  1908. this.setupComponents();
  1909. this.components.forEach(function (c) {
  1910. return c.setup(_this.drawArea);
  1911. });
  1912. // this.components.forEach(c => c.make());
  1913. this.render(this.components, false);
  1914. if (init) {
  1915. this.data = this.realData;
  1916. setTimeout(function () {
  1917. _this.update(_this.data);
  1918. }, this.initTimeout);
  1919. }
  1920. this.renderLegend();
  1921. this.setupNavigation(init);
  1922. }
  1923. }, {
  1924. key: 'calc',
  1925. value: function calc() {} // builds state
  1926. }, {
  1927. key: 'updateWidth',
  1928. value: function updateWidth() {
  1929. this.baseWidth = getElementContentWidth$1(this.parent);
  1930. this.width = this.baseWidth - getExtraWidth$1(this.measures);
  1931. }
  1932. }, {
  1933. key: 'makeChartArea',
  1934. value: function makeChartArea() {
  1935. if (this.svg) {
  1936. this.container.removeChild(this.svg);
  1937. }
  1938. var m = this.measures;
  1939. this.svg = makeSVGContainer(this.container, 'frappe-chart chart', this.baseWidth, this.baseHeight);
  1940. this.svgDefs = makeSVGDefs(this.svg);
  1941. if (this.title.length) {
  1942. this.titleEL = makeText('title', m.margins.left, m.margins.top, this.title, {
  1943. fontSize: m.titleFontSize,
  1944. fill: '#666666',
  1945. dy: m.titleFontSize
  1946. });
  1947. }
  1948. var top = getTopOffset$1(m);
  1949. this.drawArea = makeSVGGroup(this.type + '-chart chart-draw-area', 'translate(' + getLeftOffset$1(m) + ', ' + top + ')');
  1950. if (this.config.showLegend) {
  1951. top += this.height + m.paddings.bottom;
  1952. this.legendArea = makeSVGGroup('chart-legend', 'translate(' + getLeftOffset$1(m) + ', ' + top + ')');
  1953. }
  1954. if (this.title.length) {
  1955. this.svg.appendChild(this.titleEL);
  1956. }
  1957. this.svg.appendChild(this.drawArea);
  1958. if (this.config.showLegend) {
  1959. this.svg.appendChild(this.legendArea);
  1960. }
  1961. this.updateTipOffset(getLeftOffset$1(m), getTopOffset$1(m));
  1962. }
  1963. }, {
  1964. key: 'updateTipOffset',
  1965. value: function updateTipOffset(x, y) {
  1966. this.tip.offset = {
  1967. x: x,
  1968. y: y
  1969. };
  1970. }
  1971. }, {
  1972. key: 'setupComponents',
  1973. value: function setupComponents() {
  1974. this.components = new Map();
  1975. }
  1976. }, {
  1977. key: 'update',
  1978. value: function update(data) {
  1979. if (!data) {
  1980. console.error('No data to update.');
  1981. }
  1982. this.data = this.prepareData(data);
  1983. this.calc(); // builds state
  1984. this.render();
  1985. }
  1986. }, {
  1987. key: 'render',
  1988. value: function render() {
  1989. var _this2 = this;
  1990. var components = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : this.components;
  1991. var animate = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
  1992. if (this.config.isNavigable) {
  1993. // Remove all existing overlays
  1994. this.overlays.map(function (o) {
  1995. return o.parentNode.removeChild(o);
  1996. });
  1997. // ref.parentNode.insertBefore(element, ref);
  1998. }
  1999. var elementsToAnimate = [];
  2000. // Can decouple to this.refreshComponents() first to save animation timeout
  2001. components.forEach(function (c) {
  2002. elementsToAnimate = elementsToAnimate.concat(c.update(animate));
  2003. });
  2004. if (elementsToAnimate.length > 0) {
  2005. runSMILAnimation(this.container, this.svg, elementsToAnimate);
  2006. setTimeout(function () {
  2007. components.forEach(function (c) {
  2008. return c.make();
  2009. });
  2010. _this2.updateNav();
  2011. }, CHART_POST_ANIMATE_TIMEOUT$1);
  2012. } else {
  2013. components.forEach(function (c) {
  2014. return c.make();
  2015. });
  2016. this.updateNav();
  2017. }
  2018. }
  2019. }, {
  2020. key: 'updateNav',
  2021. value: function updateNav() {
  2022. if (this.config.isNavigable) {
  2023. this.makeOverlay();
  2024. this.bindUnits();
  2025. }
  2026. }
  2027. }, {
  2028. key: 'renderLegend',
  2029. value: function renderLegend() {}
  2030. }, {
  2031. key: 'setupNavigation',
  2032. value: function setupNavigation() {
  2033. var _this3 = this;
  2034. var init = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;
  2035. if (!this.config.isNavigable) return;
  2036. if (init) {
  2037. this.bindOverlay();
  2038. this.keyActions = {
  2039. '13': this.onEnterKey.bind(this),
  2040. '37': this.onLeftArrow.bind(this),
  2041. '38': this.onUpArrow.bind(this),
  2042. '39': this.onRightArrow.bind(this),
  2043. '40': this.onDownArrow.bind(this)
  2044. };
  2045. document.addEventListener('keydown', function (e) {
  2046. if (isElementInViewport$1(_this3.container)) {
  2047. e = e || window.event;
  2048. if (_this3.keyActions[e.keyCode]) {
  2049. _this3.keyActions[e.keyCode]();
  2050. }
  2051. }
  2052. });
  2053. }
  2054. }
  2055. }, {
  2056. key: 'makeOverlay',
  2057. value: function makeOverlay$$1() {}
  2058. }, {
  2059. key: 'updateOverlay',
  2060. value: function updateOverlay$$1() {}
  2061. }, {
  2062. key: 'bindOverlay',
  2063. value: function bindOverlay() {}
  2064. }, {
  2065. key: 'bindUnits',
  2066. value: function bindUnits() {}
  2067. }, {
  2068. key: 'onLeftArrow',
  2069. value: function onLeftArrow() {}
  2070. }, {
  2071. key: 'onRightArrow',
  2072. value: function onRightArrow() {}
  2073. }, {
  2074. key: 'onUpArrow',
  2075. value: function onUpArrow() {}
  2076. }, {
  2077. key: 'onDownArrow',
  2078. value: function onDownArrow() {}
  2079. }, {
  2080. key: 'onEnterKey',
  2081. value: function onEnterKey() {}
  2082. }, {
  2083. key: 'addDataPoint',
  2084. value: function addDataPoint() {}
  2085. }, {
  2086. key: 'removeDataPoint',
  2087. value: function removeDataPoint() {}
  2088. }, {
  2089. key: 'getDataPoint',
  2090. value: function getDataPoint() {}
  2091. }, {
  2092. key: 'setCurrentDataPoint',
  2093. value: function setCurrentDataPoint() {}
  2094. }, {
  2095. key: 'updateDataset',
  2096. value: function updateDataset() {}
  2097. }, {
  2098. key: 'export',
  2099. value: function _export() {
  2100. var chartSvg = prepareForExport(this.svg);
  2101. downloadFile(this.title || 'Chart', [chartSvg]);
  2102. }
  2103. }]);
  2104. return BaseChart;
  2105. }();
  2106. var _createClass$1 = function () {
  2107. function defineProperties(target, props) {
  2108. for (var i = 0; i < props.length; i++) {
  2109. 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);
  2110. }
  2111. }return function (Constructor, protoProps, staticProps) {
  2112. if (protoProps) defineProperties(Constructor.prototype, protoProps);if (staticProps) defineProperties(Constructor, staticProps);return Constructor;
  2113. };
  2114. }();
  2115. var _get$1 = function get$$1(object, property, receiver) {
  2116. if (object === null) object = Function.prototype;var desc = Object.getOwnPropertyDescriptor(object, property);if (desc === undefined) {
  2117. var parent = Object.getPrototypeOf(object);if (parent === null) {
  2118. return undefined;
  2119. } else {
  2120. return get$$1(parent, property, receiver);
  2121. }
  2122. } else if ("value" in desc) {
  2123. return desc.value;
  2124. } else {
  2125. var getter = desc.get;if (getter === undefined) {
  2126. return undefined;
  2127. }return getter.call(receiver);
  2128. }
  2129. };
  2130. function _classCallCheck$2(instance, Constructor) {
  2131. if (!(instance instanceof Constructor)) {
  2132. throw new TypeError("Cannot call a class as a function");
  2133. }
  2134. }
  2135. function _possibleConstructorReturn$1(self, call) {
  2136. if (!self) {
  2137. throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
  2138. }return call && ((typeof call === 'undefined' ? 'undefined' : _typeof2(call)) === "object" || typeof call === "function") ? call : self;
  2139. }
  2140. function _inherits$1(subClass, superClass) {
  2141. if (typeof superClass !== "function" && superClass !== null) {
  2142. throw new TypeError("Super expression must either be null or a function, not " + (typeof superClass === 'undefined' ? 'undefined' : _typeof2(superClass)));
  2143. }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;
  2144. }
  2145. var AggregationChart = function (_BaseChart) {
  2146. _inherits$1(AggregationChart, _BaseChart);
  2147. function AggregationChart(parent, args) {
  2148. _classCallCheck$2(this, AggregationChart);
  2149. return _possibleConstructorReturn$1(this, (AggregationChart.__proto__ || Object.getPrototypeOf(AggregationChart)).call(this, parent, args));
  2150. }
  2151. _createClass$1(AggregationChart, [{
  2152. key: 'configure',
  2153. value: function configure(args) {
  2154. _get$1(AggregationChart.prototype.__proto__ || Object.getPrototypeOf(AggregationChart.prototype), 'configure', this).call(this, args);
  2155. this.config.maxSlices = args.maxSlices || 20;
  2156. this.config.maxLegendPoints = args.maxLegendPoints || 20;
  2157. }
  2158. }, {
  2159. key: 'calc',
  2160. value: function calc() {
  2161. var _this2 = this;
  2162. var s = this.state;
  2163. var maxSlices = this.config.maxSlices;
  2164. s.sliceTotals = [];
  2165. var allTotals = this.data.labels.map(function (label, i) {
  2166. var total = 0;
  2167. _this2.data.datasets.map(function (e) {
  2168. total += e.values[i];
  2169. });
  2170. return [total, label];
  2171. }).filter(function (d) {
  2172. return d[0] >= 0;
  2173. }); // keep only positive results
  2174. var totals = allTotals;
  2175. if (allTotals.length > maxSlices) {
  2176. // Prune and keep a grey area for rest as per maxSlices
  2177. allTotals.sort(function (a, b) {
  2178. return b[0] - a[0];
  2179. });
  2180. totals = allTotals.slice(0, maxSlices - 1);
  2181. var remaining = allTotals.slice(maxSlices - 1);
  2182. var sumOfRemaining = 0;
  2183. remaining.map(function (d) {
  2184. sumOfRemaining += d[0];
  2185. });
  2186. totals.push([sumOfRemaining, 'Rest']);
  2187. this.colors[maxSlices - 1] = 'grey';
  2188. }
  2189. s.labels = [];
  2190. totals.map(function (d) {
  2191. s.sliceTotals.push(d[0]);
  2192. s.labels.push(d[1]);
  2193. });
  2194. s.grandTotal = s.sliceTotals.reduce(function (a, b) {
  2195. return a + b;
  2196. }, 0);
  2197. this.center = {
  2198. x: this.width / 2,
  2199. y: this.height / 2
  2200. };
  2201. }
  2202. }, {
  2203. key: 'renderLegend',
  2204. value: function renderLegend() {
  2205. var _this3 = this;
  2206. var s = this.state;
  2207. this.legendArea.textContent = '';
  2208. this.legendTotals = s.sliceTotals.slice(0, this.config.maxLegendPoints);
  2209. var count = 0;
  2210. var y = 0;
  2211. this.legendTotals.map(function (d, i) {
  2212. var barWidth = 110;
  2213. var divisor = Math.floor((_this3.width - getExtraWidth$1(_this3.measures)) / barWidth);
  2214. if (count > divisor) {
  2215. count = 0;
  2216. y += 20;
  2217. }
  2218. var x = barWidth * count + 5;
  2219. var dot = legendDot(x, y, 5, _this3.colors[i], s.labels[i] + ': ' + d);
  2220. _this3.legendArea.appendChild(dot);
  2221. count++;
  2222. });
  2223. }
  2224. }]);
  2225. return AggregationChart;
  2226. }(BaseChart);
  2227. // Playing around with dates
  2228. var NO_OF_YEAR_MONTHS = 12;
  2229. var NO_OF_DAYS_IN_WEEK = 7;
  2230. var NO_OF_MILLIS = 1000;
  2231. var SEC_IN_DAY = 86400;
  2232. var MONTH_NAMES = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
  2233. var DAY_NAMES_SHORT = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
  2234. // https://stackoverflow.com/a/11252167/6495043
  2235. function treatAsUtc(date) {
  2236. var result = new Date(date);
  2237. result.setMinutes(result.getMinutes() - result.getTimezoneOffset());
  2238. return result;
  2239. }
  2240. function getYyyyMmDd(date) {
  2241. var dd = date.getDate();
  2242. var mm = date.getMonth() + 1; // getMonth() is zero-based
  2243. return [date.getFullYear(), (mm > 9 ? '' : '0') + mm, (dd > 9 ? '' : '0') + dd].join('-');
  2244. }
  2245. function clone(date) {
  2246. return new Date(date.getTime());
  2247. }
  2248. // export function getMonthsBetween(startDate, endDate) {}
  2249. function getWeeksBetween(startDate, endDate) {
  2250. var weekStartDate = setDayToSunday(startDate);
  2251. return Math.ceil(getDaysBetween(weekStartDate, endDate) / NO_OF_DAYS_IN_WEEK);
  2252. }
  2253. function getDaysBetween(startDate, endDate) {
  2254. var millisecondsPerDay = SEC_IN_DAY * NO_OF_MILLIS;
  2255. return (treatAsUtc(endDate) - treatAsUtc(startDate)) / millisecondsPerDay;
  2256. }
  2257. function areInSameMonth(startDate, endDate) {
  2258. return startDate.getMonth() === endDate.getMonth() && startDate.getFullYear() === endDate.getFullYear();
  2259. }
  2260. function getMonthName(i) {
  2261. var short = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
  2262. var monthName = MONTH_NAMES[i];
  2263. return short ? monthName.slice(0, 3) : monthName;
  2264. }
  2265. function getLastDateInMonth(month, year) {
  2266. return new Date(year, month + 1, 0); // 0: last day in previous month
  2267. }
  2268. // mutates
  2269. function setDayToSunday(date) {
  2270. var newDate = clone(date);
  2271. var day = newDate.getDay();
  2272. if (day !== 0) {
  2273. addDays(newDate, -1 * day);
  2274. }
  2275. return newDate;
  2276. }
  2277. // mutates
  2278. function addDays(date, numberOfDays) {
  2279. date.setDate(date.getDate() + numberOfDays);
  2280. }
  2281. var _slicedToArray$3 = function () {
  2282. function sliceIterator(arr, i) {
  2283. var _arr = [];var _n = true;var _d = false;var _e = undefined;try {
  2284. for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) {
  2285. _arr.push(_s.value);if (i && _arr.length === i) break;
  2286. }
  2287. } catch (err) {
  2288. _d = true;_e = err;
  2289. } finally {
  2290. try {
  2291. if (!_n && _i["return"]) _i["return"]();
  2292. } finally {
  2293. if (_d) throw _e;
  2294. }
  2295. }return _arr;
  2296. }return function (arr, i) {
  2297. if (Array.isArray(arr)) {
  2298. return arr;
  2299. } else if (Symbol.iterator in Object(arr)) {
  2300. return sliceIterator(arr, i);
  2301. } else {
  2302. throw new TypeError("Invalid attempt to destructure non-iterable instance");
  2303. }
  2304. };
  2305. }();
  2306. var _createClass$4 = function () {
  2307. function defineProperties(target, props) {
  2308. for (var i = 0; i < props.length; i++) {
  2309. 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);
  2310. }
  2311. }return function (Constructor, protoProps, staticProps) {
  2312. if (protoProps) defineProperties(Constructor.prototype, protoProps);if (staticProps) defineProperties(Constructor, staticProps);return Constructor;
  2313. };
  2314. }();
  2315. function _classCallCheck$5(instance, Constructor) {
  2316. if (!(instance instanceof Constructor)) {
  2317. throw new TypeError("Cannot call a class as a function");
  2318. }
  2319. }
  2320. var ChartComponent = function () {
  2321. function ChartComponent(_ref) {
  2322. var _ref$layerClass = _ref.layerClass,
  2323. layerClass = _ref$layerClass === undefined ? '' : _ref$layerClass,
  2324. _ref$layerTransform = _ref.layerTransform,
  2325. layerTransform = _ref$layerTransform === undefined ? '' : _ref$layerTransform,
  2326. constants = _ref.constants,
  2327. getData = _ref.getData,
  2328. makeElements = _ref.makeElements,
  2329. animateElements = _ref.animateElements;
  2330. _classCallCheck$5(this, ChartComponent);
  2331. this.layerTransform = layerTransform;
  2332. this.constants = constants;
  2333. this.makeElements = makeElements;
  2334. this.getData = getData;
  2335. this.animateElements = animateElements;
  2336. this.store = [];
  2337. this.labels = [];
  2338. this.layerClass = layerClass;
  2339. this.layerClass = typeof this.layerClass === 'function' ? this.layerClass() : this.layerClass;
  2340. this.refresh();
  2341. }
  2342. _createClass$4(ChartComponent, [{
  2343. key: 'refresh',
  2344. value: function refresh(data) {
  2345. this.data = data || this.getData();
  2346. }
  2347. }, {
  2348. key: 'setup',
  2349. value: function setup(parent) {
  2350. this.layer = makeSVGGroup(this.layerClass, this.layerTransform, parent);
  2351. }
  2352. }, {
  2353. key: 'make',
  2354. value: function make() {
  2355. this.render(this.data);
  2356. this.oldData = this.data;
  2357. }
  2358. }, {
  2359. key: 'render',
  2360. value: function render(data) {
  2361. var _this = this;
  2362. this.store = this.makeElements(data);
  2363. this.layer.textContent = '';
  2364. this.store.forEach(function (element) {
  2365. _this.layer.appendChild(element);
  2366. });
  2367. this.labels.forEach(function (element) {
  2368. _this.layer.appendChild(element);
  2369. });
  2370. }
  2371. }, {
  2372. key: 'update',
  2373. value: function update() {
  2374. var animate = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true;
  2375. this.refresh();
  2376. var animateElements = [];
  2377. if (animate) {
  2378. animateElements = this.animateElements(this.data) || [];
  2379. }
  2380. return animateElements;
  2381. }
  2382. }]);
  2383. return ChartComponent;
  2384. }();
  2385. var componentConfigs = {
  2386. pieSlices: {
  2387. layerClass: 'pie-slices',
  2388. makeElements: function makeElements(data) {
  2389. return data.sliceStrings.map(function (s, i) {
  2390. var slice = makePath(s, 'pie-path', 'none', data.colors[i]);
  2391. slice.style.transition = 'transform .3s;';
  2392. return slice;
  2393. });
  2394. },
  2395. animateElements: function animateElements(newData) {
  2396. return this.store.map(function (slice, i) {
  2397. return animatePathStr(slice, newData.sliceStrings[i]);
  2398. });
  2399. }
  2400. },
  2401. percentageBars: {
  2402. layerClass: 'percentage-bars',
  2403. makeElements: function makeElements(data) {
  2404. var _this2 = this;
  2405. return data.xPositions.map(function (x, i) {
  2406. var y = 0;
  2407. var bar = percentageBar(x, y, data.widths[i], _this2.constants.barHeight, _this2.constants.barDepth, data.colors[i]);
  2408. return bar;
  2409. });
  2410. },
  2411. animateElements: function animateElements(newData) {
  2412. if (newData) return [];
  2413. }
  2414. },
  2415. yAxis: {
  2416. layerClass: 'y axis',
  2417. makeElements: function makeElements(data) {
  2418. var _this3 = this;
  2419. return data.positions.map(function (position, i) {
  2420. return yLine(position, data.labels[i], _this3.constants.width, { mode: _this3.constants.mode, pos: _this3.constants.pos });
  2421. });
  2422. },
  2423. animateElements: function animateElements(newData) {
  2424. var newPos = newData.positions;
  2425. var newLabels = newData.labels;
  2426. var oldPos = this.oldData.positions;
  2427. var oldLabels = this.oldData.labels;
  2428. var _equilizeNoOfElements = equilizeNoOfElements(oldPos, newPos);
  2429. var _equilizeNoOfElements2 = _slicedToArray$3(_equilizeNoOfElements, 2);
  2430. oldPos = _equilizeNoOfElements2[0];
  2431. newPos = _equilizeNoOfElements2[1];
  2432. var _equilizeNoOfElements3 = equilizeNoOfElements(oldLabels, newLabels);
  2433. var _equilizeNoOfElements4 = _slicedToArray$3(_equilizeNoOfElements3, 2);
  2434. oldLabels = _equilizeNoOfElements4[0];
  2435. newLabels = _equilizeNoOfElements4[1];
  2436. this.render({
  2437. positions: oldPos,
  2438. labels: newLabels
  2439. });
  2440. return this.store.map(function (line, i) {
  2441. return translateHoriLine(line, newPos[i], oldPos[i]);
  2442. });
  2443. }
  2444. },
  2445. xAxis: {
  2446. layerClass: 'x axis',
  2447. makeElements: function makeElements(data) {
  2448. var _this4 = this;
  2449. return data.positions.map(function (position, i) {
  2450. return xLine(position, data.calcLabels[i], _this4.constants.height, { mode: _this4.constants.mode, pos: _this4.constants.pos });
  2451. });
  2452. },
  2453. animateElements: function animateElements(newData) {
  2454. var newPos = newData.positions;
  2455. var newLabels = newData.calcLabels;
  2456. var oldPos = this.oldData.positions;
  2457. var oldLabels = this.oldData.calcLabels;
  2458. var _equilizeNoOfElements5 = equilizeNoOfElements(oldPos, newPos);
  2459. var _equilizeNoOfElements6 = _slicedToArray$3(_equilizeNoOfElements5, 2);
  2460. oldPos = _equilizeNoOfElements6[0];
  2461. newPos = _equilizeNoOfElements6[1];
  2462. var _equilizeNoOfElements7 = equilizeNoOfElements(oldLabels, newLabels);
  2463. var _equilizeNoOfElements8 = _slicedToArray$3(_equilizeNoOfElements7, 2);
  2464. oldLabels = _equilizeNoOfElements8[0];
  2465. newLabels = _equilizeNoOfElements8[1];
  2466. this.render({
  2467. positions: oldPos,
  2468. calcLabels: newLabels
  2469. });
  2470. return this.store.map(function (line, i) {
  2471. return translateVertLine(line, newPos[i], oldPos[i]);
  2472. });
  2473. }
  2474. },
  2475. yMarkers: {
  2476. layerClass: 'y-markers',
  2477. makeElements: function makeElements(data) {
  2478. var _this5 = this;
  2479. return data.map(function (m) {
  2480. return yMarker(m.position, m.label, _this5.constants.width, { labelPos: m.options.labelPos, mode: 'span', lineType: 'dashed' });
  2481. });
  2482. },
  2483. animateElements: function animateElements(newData) {
  2484. var _equilizeNoOfElements9 = equilizeNoOfElements(this.oldData, newData);
  2485. var _equilizeNoOfElements10 = _slicedToArray$3(_equilizeNoOfElements9, 2);
  2486. this.oldData = _equilizeNoOfElements10[0];
  2487. newData = _equilizeNoOfElements10[1];
  2488. var newPos = newData.map(function (d) {
  2489. return d.position;
  2490. });
  2491. var newLabels = newData.map(function (d) {
  2492. return d.label;
  2493. });
  2494. var newOptions = newData.map(function (d) {
  2495. return d.options;
  2496. });
  2497. var oldPos = this.oldData.map(function (d) {
  2498. return d.position;
  2499. });
  2500. this.render(oldPos.map(function (pos, i) {
  2501. return {
  2502. position: oldPos[i],
  2503. label: newLabels[i],
  2504. options: newOptions[i]
  2505. };
  2506. }));
  2507. return this.store.map(function (line, i) {
  2508. return translateHoriLine(line, newPos[i], oldPos[i]);
  2509. });
  2510. }
  2511. },
  2512. yRegions: {
  2513. layerClass: 'y-regions',
  2514. makeElements: function makeElements(data) {
  2515. var _this6 = this;
  2516. return data.map(function (r) {
  2517. return yRegion(r.startPos, r.endPos, _this6.constants.width, r.label, { labelPos: r.options.labelPos });
  2518. });
  2519. },
  2520. animateElements: function animateElements(newData) {
  2521. var _equilizeNoOfElements11 = equilizeNoOfElements(this.oldData, newData);
  2522. var _equilizeNoOfElements12 = _slicedToArray$3(_equilizeNoOfElements11, 2);
  2523. this.oldData = _equilizeNoOfElements12[0];
  2524. newData = _equilizeNoOfElements12[1];
  2525. var newPos = newData.map(function (d) {
  2526. return d.endPos;
  2527. });
  2528. var newLabels = newData.map(function (d) {
  2529. return d.label;
  2530. });
  2531. var newStarts = newData.map(function (d) {
  2532. return d.startPos;
  2533. });
  2534. var newOptions = newData.map(function (d) {
  2535. return d.options;
  2536. });
  2537. var oldPos = this.oldData.map(function (d) {
  2538. return d.endPos;
  2539. });
  2540. var oldStarts = this.oldData.map(function (d) {
  2541. return d.startPos;
  2542. });
  2543. this.render(oldPos.map(function (pos, i) {
  2544. return {
  2545. startPos: oldStarts[i],
  2546. endPos: oldPos[i],
  2547. label: newLabels[i],
  2548. options: newOptions[i]
  2549. };
  2550. }));
  2551. var animateElements = [];
  2552. this.store.map(function (rectGroup, i) {
  2553. animateElements = animateElements.concat(animateRegion(rectGroup, newStarts[i], newPos[i], oldPos[i]));
  2554. });
  2555. return animateElements;
  2556. }
  2557. },
  2558. heatDomain: {
  2559. layerClass: function layerClass() {
  2560. return 'heat-domain domain-' + this.constants.index;
  2561. },
  2562. makeElements: function makeElements(data) {
  2563. var _this7 = this;
  2564. var _constants = this.constants,
  2565. index = _constants.index,
  2566. colWidth = _constants.colWidth,
  2567. rowHeight = _constants.rowHeight,
  2568. squareSize = _constants.squareSize,
  2569. xTranslate = _constants.xTranslate;
  2570. var monthNameHeight = -12;
  2571. var x = xTranslate,
  2572. y = 0;
  2573. this.serializedSubDomains = [];
  2574. data.cols.map(function (week, weekNo) {
  2575. if (weekNo === 1) {
  2576. _this7.labels.push(makeText('domain-name', x, monthNameHeight, getMonthName(index, true).toUpperCase(), {
  2577. fontSize: 9
  2578. }));
  2579. }
  2580. week.map(function (day, i) {
  2581. if (day.fill) {
  2582. var _data = {
  2583. 'data-date': day.yyyyMmDd,
  2584. 'data-value': day.dataValue,
  2585. 'data-day': i
  2586. };
  2587. var square = heatSquare('day', x, y, squareSize, day.fill, _data);
  2588. _this7.serializedSubDomains.push(square);
  2589. }
  2590. y += rowHeight;
  2591. });
  2592. y = 0;
  2593. x += colWidth;
  2594. });
  2595. return this.serializedSubDomains;
  2596. },
  2597. animateElements: function animateElements(newData) {
  2598. if (newData) return [];
  2599. }
  2600. },
  2601. barGraph: {
  2602. layerClass: function layerClass() {
  2603. return 'dataset-units dataset-bars dataset-' + this.constants.index;
  2604. },
  2605. makeElements: function makeElements(data) {
  2606. var c = this.constants;
  2607. this.unitType = 'bar';
  2608. this.units = data.yPositions.map(function (y, j) {
  2609. return datasetBar(data.xPositions[j], y, data.barWidth, c.color, data.labels[j], j, data.offsets[j], {
  2610. zeroLine: data.zeroLine,
  2611. barsWidth: data.barsWidth,
  2612. minHeight: c.minHeight
  2613. });
  2614. });
  2615. return this.units;
  2616. },
  2617. animateElements: function animateElements(newData) {
  2618. var newXPos = newData.xPositions;
  2619. var newYPos = newData.yPositions;
  2620. var newOffsets = newData.offsets;
  2621. var newLabels = newData.labels;
  2622. var oldXPos = this.oldData.xPositions;
  2623. var oldYPos = this.oldData.yPositions;
  2624. var oldOffsets = this.oldData.offsets;
  2625. var oldLabels = this.oldData.labels;
  2626. var _equilizeNoOfElements13 = equilizeNoOfElements(oldXPos, newXPos);
  2627. var _equilizeNoOfElements14 = _slicedToArray$3(_equilizeNoOfElements13, 2);
  2628. oldXPos = _equilizeNoOfElements14[0];
  2629. newXPos = _equilizeNoOfElements14[1];
  2630. var _equilizeNoOfElements15 = equilizeNoOfElements(oldYPos, newYPos);
  2631. var _equilizeNoOfElements16 = _slicedToArray$3(_equilizeNoOfElements15, 2);
  2632. oldYPos = _equilizeNoOfElements16[0];
  2633. newYPos = _equilizeNoOfElements16[1];
  2634. var _equilizeNoOfElements17 = equilizeNoOfElements(oldOffsets, newOffsets);
  2635. var _equilizeNoOfElements18 = _slicedToArray$3(_equilizeNoOfElements17, 2);
  2636. oldOffsets = _equilizeNoOfElements18[0];
  2637. newOffsets = _equilizeNoOfElements18[1];
  2638. var _equilizeNoOfElements19 = equilizeNoOfElements(oldLabels, newLabels);
  2639. var _equilizeNoOfElements20 = _slicedToArray$3(_equilizeNoOfElements19, 2);
  2640. oldLabels = _equilizeNoOfElements20[0];
  2641. newLabels = _equilizeNoOfElements20[1];
  2642. this.render({
  2643. xPositions: oldXPos,
  2644. yPositions: oldYPos,
  2645. offsets: oldOffsets,
  2646. labels: newLabels,
  2647. zeroLine: this.oldData.zeroLine,
  2648. barsWidth: this.oldData.barsWidth,
  2649. barWidth: this.oldData.barWidth
  2650. });
  2651. var animateElements = [];
  2652. this.store.map(function (bar, i) {
  2653. animateElements = animateElements.concat(animateBar(bar, newXPos[i], newYPos[i], newData.barWidth, newOffsets[i], { zeroLine: newData.zeroLine }));
  2654. });
  2655. return animateElements;
  2656. }
  2657. },
  2658. lineGraph: {
  2659. layerClass: function layerClass() {
  2660. return 'dataset-units dataset-line dataset-' + this.constants.index;
  2661. },
  2662. makeElements: function makeElements(data) {
  2663. var c = this.constants;
  2664. this.unitType = 'dot';
  2665. this.paths = {};
  2666. if (!c.hideLine) {
  2667. this.paths = getPaths(data.xPositions, data.yPositions, c.color, {
  2668. heatline: c.heatline,
  2669. areaFill: c.areaFill
  2670. }, {
  2671. svgDefs: c.svgDefs,
  2672. zeroLine: data.zeroLine
  2673. });
  2674. }
  2675. this.units = [];
  2676. if (!c.hideDots) {
  2677. this.units = data.yPositions.map(function (y, j) {
  2678. return datasetDot(data.xPositions[j], y, data.radius, c.color, c.valuesOverPoints ? data.values[j] : '', j);
  2679. });
  2680. }
  2681. return Object.values(this.paths).concat(this.units);
  2682. },
  2683. animateElements: function animateElements(newData) {
  2684. var newXPos = newData.xPositions;
  2685. var newYPos = newData.yPositions;
  2686. var newValues = newData.values;
  2687. var oldXPos = this.oldData.xPositions;
  2688. var oldYPos = this.oldData.yPositions;
  2689. var oldValues = this.oldData.values;
  2690. var _equilizeNoOfElements21 = equilizeNoOfElements(oldXPos, newXPos);
  2691. var _equilizeNoOfElements22 = _slicedToArray$3(_equilizeNoOfElements21, 2);
  2692. oldXPos = _equilizeNoOfElements22[0];
  2693. newXPos = _equilizeNoOfElements22[1];
  2694. var _equilizeNoOfElements23 = equilizeNoOfElements(oldYPos, newYPos);
  2695. var _equilizeNoOfElements24 = _slicedToArray$3(_equilizeNoOfElements23, 2);
  2696. oldYPos = _equilizeNoOfElements24[0];
  2697. newYPos = _equilizeNoOfElements24[1];
  2698. var _equilizeNoOfElements25 = equilizeNoOfElements(oldValues, newValues);
  2699. var _equilizeNoOfElements26 = _slicedToArray$3(_equilizeNoOfElements25, 2);
  2700. oldValues = _equilizeNoOfElements26[0];
  2701. newValues = _equilizeNoOfElements26[1];
  2702. this.render({
  2703. xPositions: oldXPos,
  2704. yPositions: oldYPos,
  2705. values: newValues,
  2706. zeroLine: this.oldData.zeroLine,
  2707. radius: this.oldData.radius
  2708. });
  2709. var animateElements = [];
  2710. if (Object.keys(this.paths).length) {
  2711. animateElements = animateElements.concat(animatePath(this.paths, newXPos, newYPos, newData.zeroLine));
  2712. }
  2713. if (this.units.length) {
  2714. this.units.map(function (dot, i) {
  2715. animateElements = animateElements.concat(animateDot(dot, newXPos[i], newYPos[i]));
  2716. });
  2717. }
  2718. return animateElements;
  2719. }
  2720. }
  2721. };
  2722. function getComponent(name, constants, getData) {
  2723. var keys = Object.keys(componentConfigs).filter(function (k) {
  2724. return name.includes(k);
  2725. });
  2726. var config = componentConfigs[keys[0]];
  2727. Object.assign(config, {
  2728. constants: constants,
  2729. getData: getData
  2730. });
  2731. return new ChartComponent(config);
  2732. }
  2733. var _createClass$1$1 = function () {
  2734. function defineProperties(target, props) {
  2735. for (var i = 0; i < props.length; i++) {
  2736. 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);
  2737. }
  2738. }return function (Constructor, protoProps, staticProps) {
  2739. if (protoProps) defineProperties(Constructor.prototype, protoProps);if (staticProps) defineProperties(Constructor, staticProps);return Constructor;
  2740. };
  2741. }();
  2742. var _get = function get$$1(object, property, receiver) {
  2743. if (object === null) object = Function.prototype;var desc = Object.getOwnPropertyDescriptor(object, property);if (desc === undefined) {
  2744. var parent = Object.getPrototypeOf(object);if (parent === null) {
  2745. return undefined;
  2746. } else {
  2747. return get$$1(parent, property, receiver);
  2748. }
  2749. } else if ("value" in desc) {
  2750. return desc.value;
  2751. } else {
  2752. var getter = desc.get;if (getter === undefined) {
  2753. return undefined;
  2754. }return getter.call(receiver);
  2755. }
  2756. };
  2757. function _toConsumableArray$1$1(arr) {
  2758. if (Array.isArray(arr)) {
  2759. for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) {
  2760. arr2[i] = arr[i];
  2761. }return arr2;
  2762. } else {
  2763. return Array.from(arr);
  2764. }
  2765. }
  2766. function _classCallCheck$1(instance, Constructor) {
  2767. if (!(instance instanceof Constructor)) {
  2768. throw new TypeError("Cannot call a class as a function");
  2769. }
  2770. }
  2771. function _possibleConstructorReturn(self, call) {
  2772. if (!self) {
  2773. throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
  2774. }return call && ((typeof call === 'undefined' ? 'undefined' : _typeof2(call)) === "object" || typeof call === "function") ? call : self;
  2775. }
  2776. function _inherits(subClass, superClass) {
  2777. if (typeof superClass !== "function" && superClass !== null) {
  2778. throw new TypeError("Super expression must either be null or a function, not " + (typeof superClass === 'undefined' ? 'undefined' : _typeof2(superClass)));
  2779. }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;
  2780. }
  2781. var PercentageChart = function (_AggregationChart) {
  2782. _inherits(PercentageChart, _AggregationChart);
  2783. function PercentageChart(parent, args) {
  2784. _classCallCheck$1(this, PercentageChart);
  2785. var _this = _possibleConstructorReturn(this, (PercentageChart.__proto__ || Object.getPrototypeOf(PercentageChart)).call(this, parent, args));
  2786. _this.type = 'percentage';
  2787. _this.setup();
  2788. return _this;
  2789. }
  2790. _createClass$1$1(PercentageChart, [{
  2791. key: 'setMeasures',
  2792. value: function setMeasures(options) {
  2793. var m = this.measures;
  2794. this.barOptions = options.barOptions || {};
  2795. var b = this.barOptions;
  2796. b.height = b.height || PERCENTAGE_BAR_DEFAULT_HEIGHT$1;
  2797. b.depth = b.depth || PERCENTAGE_BAR_DEFAULT_DEPTH$1;
  2798. m.paddings.right = 30;
  2799. m.legendHeight = 80;
  2800. m.baseHeight = (b.height + b.depth * 0.5) * 8;
  2801. }
  2802. }, {
  2803. key: 'setupComponents',
  2804. value: function setupComponents() {
  2805. var s = this.state;
  2806. var componentConfigs = [['percentageBars', {
  2807. barHeight: this.barOptions.height,
  2808. barDepth: this.barOptions.depth
  2809. }, function () {
  2810. return {
  2811. xPositions: s.xPositions,
  2812. widths: s.widths,
  2813. colors: this.colors
  2814. };
  2815. }.bind(this)]];
  2816. this.components = new Map(componentConfigs.map(function (args) {
  2817. var component = getComponent.apply(undefined, _toConsumableArray$1$1(args));
  2818. return [args[0], component];
  2819. }));
  2820. }
  2821. }, {
  2822. key: 'calc',
  2823. value: function calc() {
  2824. var _this2 = this;
  2825. _get(PercentageChart.prototype.__proto__ || Object.getPrototypeOf(PercentageChart.prototype), 'calc', this).call(this);
  2826. var s = this.state;
  2827. s.xPositions = [];
  2828. s.widths = [];
  2829. var xPos = 0;
  2830. s.sliceTotals.map(function (value) {
  2831. var width = _this2.width * value / s.grandTotal;
  2832. s.widths.push(width);
  2833. s.xPositions.push(xPos);
  2834. xPos += width;
  2835. });
  2836. }
  2837. }, {
  2838. key: 'makeDataByIndex',
  2839. value: function makeDataByIndex() {}
  2840. }, {
  2841. key: 'bindTooltip',
  2842. value: function bindTooltip() {
  2843. var _this3 = this;
  2844. var s = this.state;
  2845. this.container.addEventListener('mousemove', function (e) {
  2846. var bars = _this3.components.get('percentageBars').store;
  2847. var bar = e.target;
  2848. if (bars.includes(bar)) {
  2849. var i = bars.indexOf(bar);
  2850. var gOff = getOffset$1(_this3.container),
  2851. pOff = getOffset$1(bar);
  2852. var x = pOff.left - gOff.left + parseInt(bar.getAttribute('width')) / 2;
  2853. var y = pOff.top - gOff.top;
  2854. var title = (_this3.formattedLabels && _this3.formattedLabels.length > 0 ? _this3.formattedLabels[i] : _this3.state.labels[i]) + ': ';
  2855. var fraction = s.sliceTotals[i] / s.grandTotal;
  2856. _this3.tip.setValues(x, y, { name: title, value: (fraction * 100).toFixed(1) + "%" });
  2857. _this3.tip.showTip();
  2858. }
  2859. });
  2860. }
  2861. }]);
  2862. return PercentageChart;
  2863. }(AggregationChart);
  2864. var _createClass$5 = function () {
  2865. function defineProperties(target, props) {
  2866. for (var i = 0; i < props.length; i++) {
  2867. 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);
  2868. }
  2869. }return function (Constructor, protoProps, staticProps) {
  2870. if (protoProps) defineProperties(Constructor.prototype, protoProps);if (staticProps) defineProperties(Constructor, staticProps);return Constructor;
  2871. };
  2872. }();
  2873. var _get$2 = function get$$1(object, property, receiver) {
  2874. if (object === null) object = Function.prototype;var desc = Object.getOwnPropertyDescriptor(object, property);if (desc === undefined) {
  2875. var parent = Object.getPrototypeOf(object);if (parent === null) {
  2876. return undefined;
  2877. } else {
  2878. return get$$1(parent, property, receiver);
  2879. }
  2880. } else if ("value" in desc) {
  2881. return desc.value;
  2882. } else {
  2883. var getter = desc.get;if (getter === undefined) {
  2884. return undefined;
  2885. }return getter.call(receiver);
  2886. }
  2887. };
  2888. function _toConsumableArray$2(arr) {
  2889. if (Array.isArray(arr)) {
  2890. for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) {
  2891. arr2[i] = arr[i];
  2892. }return arr2;
  2893. } else {
  2894. return Array.from(arr);
  2895. }
  2896. }
  2897. function _classCallCheck$6(instance, Constructor) {
  2898. if (!(instance instanceof Constructor)) {
  2899. throw new TypeError("Cannot call a class as a function");
  2900. }
  2901. }
  2902. function _possibleConstructorReturn$2(self, call) {
  2903. if (!self) {
  2904. throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
  2905. }return call && ((typeof call === 'undefined' ? 'undefined' : _typeof2(call)) === "object" || typeof call === "function") ? call : self;
  2906. }
  2907. function _inherits$2(subClass, superClass) {
  2908. if (typeof superClass !== "function" && superClass !== null) {
  2909. throw new TypeError("Super expression must either be null or a function, not " + (typeof superClass === 'undefined' ? 'undefined' : _typeof2(superClass)));
  2910. }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;
  2911. }
  2912. var PieChart = function (_AggregationChart) {
  2913. _inherits$2(PieChart, _AggregationChart);
  2914. function PieChart(parent, args) {
  2915. _classCallCheck$6(this, PieChart);
  2916. var _this = _possibleConstructorReturn$2(this, (PieChart.__proto__ || Object.getPrototypeOf(PieChart)).call(this, parent, args));
  2917. _this.type = 'pie';
  2918. _this.initTimeout = 0;
  2919. _this.init = 1;
  2920. _this.setup();
  2921. return _this;
  2922. }
  2923. _createClass$5(PieChart, [{
  2924. key: 'configure',
  2925. value: function configure(args) {
  2926. _get$2(PieChart.prototype.__proto__ || Object.getPrototypeOf(PieChart.prototype), 'configure', this).call(this, args);
  2927. this.mouseMove = this.mouseMove.bind(this);
  2928. this.mouseLeave = this.mouseLeave.bind(this);
  2929. this.hoverRadio = args.hoverRadio || 0.1;
  2930. this.config.startAngle = args.startAngle || 0;
  2931. this.clockWise = args.clockWise || false;
  2932. }
  2933. }, {
  2934. key: 'calc',
  2935. value: function calc() {
  2936. var _this2 = this;
  2937. _get$2(PieChart.prototype.__proto__ || Object.getPrototypeOf(PieChart.prototype), 'calc', this).call(this);
  2938. var s = this.state;
  2939. this.radius = this.height > this.width ? this.center.x : this.center.y;
  2940. var radius = this.radius,
  2941. clockWise = this.clockWise;
  2942. var prevSlicesProperties = s.slicesProperties || [];
  2943. s.sliceStrings = [];
  2944. s.slicesProperties = [];
  2945. var curAngle = 180 - this.config.startAngle;
  2946. s.sliceTotals.map(function (total, i) {
  2947. var startAngle = curAngle;
  2948. var originDiffAngle = total / s.grandTotal * FULL_ANGLE$1;
  2949. var diffAngle = clockWise ? -originDiffAngle : originDiffAngle;
  2950. var endAngle = curAngle = curAngle + diffAngle;
  2951. var startPosition = getPositionByAngle$1(startAngle, radius);
  2952. var endPosition = getPositionByAngle$1(endAngle, radius);
  2953. var prevProperty = _this2.init && prevSlicesProperties[i];
  2954. var curStart = void 0,
  2955. curEnd = void 0;
  2956. if (_this2.init) {
  2957. curStart = prevProperty ? prevProperty.startPosition : startPosition;
  2958. curEnd = prevProperty ? prevProperty.endPosition : startPosition;
  2959. } else {
  2960. curStart = startPosition;
  2961. curEnd = endPosition;
  2962. }
  2963. var curPath = makeArcPathStr(curStart, curEnd, _this2.center, _this2.radius, _this2.clockWise);
  2964. s.sliceStrings.push(curPath);
  2965. s.slicesProperties.push({
  2966. startPosition: startPosition,
  2967. endPosition: endPosition,
  2968. value: total,
  2969. total: s.grandTotal,
  2970. startAngle: startAngle,
  2971. endAngle: endAngle,
  2972. angle: diffAngle
  2973. });
  2974. });
  2975. this.init = 0;
  2976. }
  2977. }, {
  2978. key: 'setupComponents',
  2979. value: function setupComponents() {
  2980. var s = this.state;
  2981. var componentConfigs = [['pieSlices', {}, function () {
  2982. return {
  2983. sliceStrings: s.sliceStrings,
  2984. colors: this.colors
  2985. };
  2986. }.bind(this)]];
  2987. this.components = new Map(componentConfigs.map(function (args) {
  2988. var component = getComponent.apply(undefined, _toConsumableArray$2(args));
  2989. return [args[0], component];
  2990. }));
  2991. }
  2992. }, {
  2993. key: 'calTranslateByAngle',
  2994. value: function calTranslateByAngle(property) {
  2995. var radius = this.radius,
  2996. hoverRadio = this.hoverRadio;
  2997. var position = getPositionByAngle$1(property.startAngle + property.angle / 2, radius);
  2998. return 'translate3d(' + position.x * hoverRadio + 'px,' + position.y * hoverRadio + 'px,0)';
  2999. }
  3000. }, {
  3001. key: 'hoverSlice',
  3002. value: function hoverSlice(path, i, flag, e) {
  3003. if (!path) return;
  3004. var color = this.colors[i];
  3005. if (flag) {
  3006. transform(path, this.calTranslateByAngle(this.state.slicesProperties[i]));
  3007. path.style.fill = lightenDarkenColor(color, 50);
  3008. var g_off = getOffset$1(this.svg);
  3009. var x = e.pageX - g_off.left + 10;
  3010. var y = e.pageY - g_off.top - 10;
  3011. var title = (this.formatted_labels && this.formatted_labels.length > 0 ? this.formatted_labels[i] : this.state.labels[i]) + ': ';
  3012. var percent = (this.state.sliceTotals[i] * 100 / this.state.grandTotal).toFixed(1);
  3013. this.tip.setValues(x, y, { name: title, value: percent + "%" });
  3014. this.tip.showTip();
  3015. } else {
  3016. transform(path, 'translate3d(0,0,0)');
  3017. this.tip.hideTip();
  3018. path.style.fill = color;
  3019. }
  3020. }
  3021. }, {
  3022. key: 'bindTooltip',
  3023. value: function bindTooltip() {
  3024. this.container.addEventListener('mousemove', this.mouseMove);
  3025. this.container.addEventListener('mouseleave', this.mouseLeave);
  3026. }
  3027. }, {
  3028. key: 'mouseMove',
  3029. value: function mouseMove(e) {
  3030. var target = e.target;
  3031. var slices = this.components.get('pieSlices').store;
  3032. var prevIndex = this.curActiveSliceIndex;
  3033. var prevAcitve = this.curActiveSlice;
  3034. if (slices.includes(target)) {
  3035. var i = slices.indexOf(target);
  3036. this.hoverSlice(prevAcitve, prevIndex, false);
  3037. this.curActiveSlice = target;
  3038. this.curActiveSliceIndex = i;
  3039. this.hoverSlice(target, i, true, e);
  3040. } else {
  3041. this.mouseLeave();
  3042. }
  3043. }
  3044. }, {
  3045. key: 'mouseLeave',
  3046. value: function mouseLeave() {
  3047. this.hoverSlice(this.curActiveSlice, this.curActiveSliceIndex, false);
  3048. }
  3049. }]);
  3050. return PieChart;
  3051. }(AggregationChart);
  3052. var _slicedToArray$4 = function () {
  3053. function sliceIterator(arr, i) {
  3054. var _arr = [];var _n = true;var _d = false;var _e = undefined;try {
  3055. for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) {
  3056. _arr.push(_s.value);if (i && _arr.length === i) break;
  3057. }
  3058. } catch (err) {
  3059. _d = true;_e = err;
  3060. } finally {
  3061. try {
  3062. if (!_n && _i["return"]) _i["return"]();
  3063. } finally {
  3064. if (_d) throw _e;
  3065. }
  3066. }return _arr;
  3067. }return function (arr, i) {
  3068. if (Array.isArray(arr)) {
  3069. return arr;
  3070. } else if (Symbol.iterator in Object(arr)) {
  3071. return sliceIterator(arr, i);
  3072. } else {
  3073. throw new TypeError("Invalid attempt to destructure non-iterable instance");
  3074. }
  3075. };
  3076. }();
  3077. function _toConsumableArray$4(arr) {
  3078. if (Array.isArray(arr)) {
  3079. for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) {
  3080. arr2[i] = arr[i];
  3081. }return arr2;
  3082. } else {
  3083. return Array.from(arr);
  3084. }
  3085. }
  3086. function normalize(x) {
  3087. // Calculates mantissa and exponent of a number
  3088. // Returns normalized number and exponent
  3089. // https://stackoverflow.com/q/9383593/6495043
  3090. if (x === 0) {
  3091. return [0, 0];
  3092. }
  3093. if (isNaN(x)) {
  3094. return { mantissa: -6755399441055744, exponent: 972 };
  3095. }
  3096. var sig = x > 0 ? 1 : -1;
  3097. if (!isFinite(x)) {
  3098. return { mantissa: sig * 4503599627370496, exponent: 972 };
  3099. }
  3100. x = Math.abs(x);
  3101. var exp = Math.floor(Math.log10(x));
  3102. var man = x / Math.pow(10, exp);
  3103. return [sig * man, exp];
  3104. }
  3105. function getChartRangeIntervals(max) {
  3106. var min = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;
  3107. var upperBound = Math.ceil(max);
  3108. var lowerBound = Math.floor(min);
  3109. var range = upperBound - lowerBound;
  3110. var noOfParts = range;
  3111. var partSize = 1;
  3112. // To avoid too many partitions
  3113. if (range > 5) {
  3114. if (range % 2 !== 0) {
  3115. upperBound++;
  3116. // Recalc range
  3117. range = upperBound - lowerBound;
  3118. }
  3119. noOfParts = range / 2;
  3120. partSize = 2;
  3121. }
  3122. // Special case: 1 and 2
  3123. if (range <= 2) {
  3124. noOfParts = 4;
  3125. partSize = range / noOfParts;
  3126. }
  3127. // Special case: 0
  3128. if (range === 0) {
  3129. noOfParts = 5;
  3130. partSize = 1;
  3131. }
  3132. var intervals = [];
  3133. for (var i = 0; i <= noOfParts; i++) {
  3134. intervals.push(lowerBound + partSize * i);
  3135. }
  3136. return intervals;
  3137. }
  3138. function getChartIntervals(maxValue) {
  3139. var minValue = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;
  3140. var _normalize = normalize(maxValue),
  3141. _normalize2 = _slicedToArray$4(_normalize, 2),
  3142. normalMaxValue = _normalize2[0],
  3143. exponent = _normalize2[1];
  3144. var normalMinValue = minValue ? minValue / Math.pow(10, exponent) : 0;
  3145. // Allow only 7 significant digits
  3146. normalMaxValue = normalMaxValue.toFixed(6);
  3147. var intervals = getChartRangeIntervals(normalMaxValue, normalMinValue);
  3148. intervals = intervals.map(function (value) {
  3149. return value * Math.pow(10, exponent);
  3150. });
  3151. return intervals;
  3152. }
  3153. function calcChartIntervals(values) {
  3154. var withMinimum = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
  3155. //*** Where the magic happens ***
  3156. // Calculates best-fit y intervals from given values
  3157. // and returns the interval array
  3158. var maxValue = Math.max.apply(Math, _toConsumableArray$4(values));
  3159. var minValue = Math.min.apply(Math, _toConsumableArray$4(values));
  3160. // Exponent to be used for pretty print
  3161. var exponent = 0,
  3162. intervals = []; // eslint-disable-line no-unused-vars
  3163. function getPositiveFirstIntervals(maxValue, absMinValue) {
  3164. var intervals = getChartIntervals(maxValue);
  3165. var intervalSize = intervals[1] - intervals[0];
  3166. // Then unshift the negative values
  3167. var value = 0;
  3168. for (var i = 1; value < absMinValue; i++) {
  3169. value += intervalSize;
  3170. intervals.unshift(-1 * value);
  3171. }
  3172. return intervals;
  3173. }
  3174. // CASE I: Both non-negative
  3175. if (maxValue >= 0 && minValue >= 0) {
  3176. exponent = normalize(maxValue)[1];
  3177. if (!withMinimum) {
  3178. intervals = getChartIntervals(maxValue);
  3179. } else {
  3180. intervals = getChartIntervals(maxValue, minValue);
  3181. }
  3182. }
  3183. // CASE II: Only minValue negative
  3184. else if (maxValue > 0 && minValue < 0) {
  3185. // `withMinimum` irrelevant in this case,
  3186. // We'll be handling both sides of zero separately
  3187. // (both starting from zero)
  3188. // Because ceil() and floor() behave differently
  3189. // in those two regions
  3190. var absMinValue = Math.abs(minValue);
  3191. if (maxValue >= absMinValue) {
  3192. exponent = normalize(maxValue)[1];
  3193. intervals = getPositiveFirstIntervals(maxValue, absMinValue);
  3194. } else {
  3195. // Mirror: maxValue => absMinValue, then change sign
  3196. exponent = normalize(absMinValue)[1];
  3197. var posIntervals = getPositiveFirstIntervals(absMinValue, maxValue);
  3198. intervals = posIntervals.map(function (d) {
  3199. return d * -1;
  3200. });
  3201. }
  3202. }
  3203. // CASE III: Both non-positive
  3204. else if (maxValue <= 0 && minValue <= 0) {
  3205. // Mirrored Case I:
  3206. // Work with positives, then reverse the sign and array
  3207. var pseudoMaxValue = Math.abs(minValue);
  3208. var pseudoMinValue = Math.abs(maxValue);
  3209. exponent = normalize(pseudoMaxValue)[1];
  3210. if (!withMinimum) {
  3211. intervals = getChartIntervals(pseudoMaxValue);
  3212. } else {
  3213. intervals = getChartIntervals(pseudoMaxValue, pseudoMinValue);
  3214. }
  3215. intervals = intervals.reverse().map(function (d) {
  3216. return d * -1;
  3217. });
  3218. }
  3219. return intervals;
  3220. }
  3221. function getZeroIndex(yPts) {
  3222. var zeroIndex = void 0;
  3223. var interval = getIntervalSize(yPts);
  3224. if (yPts.indexOf(0) >= 0) {
  3225. // the range has a given zero
  3226. // zero-line on the chart
  3227. zeroIndex = yPts.indexOf(0);
  3228. } else if (yPts[0] > 0) {
  3229. // Minimum value is positive
  3230. // zero-line is off the chart: below
  3231. var min = yPts[0];
  3232. zeroIndex = -1 * min / interval;
  3233. } else {
  3234. // Maximum value is negative
  3235. // zero-line is off the chart: above
  3236. var max = yPts[yPts.length - 1];
  3237. zeroIndex = -1 * max / interval + (yPts.length - 1);
  3238. }
  3239. return zeroIndex;
  3240. }
  3241. function getIntervalSize(orderedArray) {
  3242. return orderedArray[1] - orderedArray[0];
  3243. }
  3244. function getValueRange(orderedArray) {
  3245. return orderedArray[orderedArray.length - 1] - orderedArray[0];
  3246. }
  3247. function scale(val, yAxis) {
  3248. return floatTwo$1(yAxis.zeroLine - val * yAxis.scaleMultiplier);
  3249. }
  3250. function getClosestInArray(goal, arr) {
  3251. var index = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
  3252. var closest = arr.reduce(function (prev, curr) {
  3253. return Math.abs(curr - goal) < Math.abs(prev - goal) ? curr : prev;
  3254. });
  3255. return index ? arr.indexOf(closest) : closest;
  3256. }
  3257. function calcDistribution(values, distributionSize) {
  3258. // Assume non-negative values,
  3259. // implying distribution minimum at zero
  3260. var dataMaxValue = Math.max.apply(Math, _toConsumableArray$4(values));
  3261. var distributionStep = 1 / (distributionSize - 1);
  3262. var distribution = [];
  3263. for (var i = 0; i < distributionSize; i++) {
  3264. var checkpoint = dataMaxValue * (distributionStep * i);
  3265. distribution.push(checkpoint);
  3266. }
  3267. return distribution;
  3268. }
  3269. function getMaxCheckpoint(value, distribution) {
  3270. return distribution.filter(function (d) {
  3271. return d < value;
  3272. }).length;
  3273. }
  3274. var _createClass$6 = function () {
  3275. function defineProperties(target, props) {
  3276. for (var i = 0; i < props.length; i++) {
  3277. 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);
  3278. }
  3279. }return function (Constructor, protoProps, staticProps) {
  3280. if (protoProps) defineProperties(Constructor.prototype, protoProps);if (staticProps) defineProperties(Constructor, staticProps);return Constructor;
  3281. };
  3282. }();
  3283. function _toConsumableArray$3(arr) {
  3284. if (Array.isArray(arr)) {
  3285. for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) {
  3286. arr2[i] = arr[i];
  3287. }return arr2;
  3288. } else {
  3289. return Array.from(arr);
  3290. }
  3291. }
  3292. function _classCallCheck$7(instance, Constructor) {
  3293. if (!(instance instanceof Constructor)) {
  3294. throw new TypeError("Cannot call a class as a function");
  3295. }
  3296. }
  3297. function _possibleConstructorReturn$3(self, call) {
  3298. if (!self) {
  3299. throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
  3300. }return call && ((typeof call === 'undefined' ? 'undefined' : _typeof2(call)) === "object" || typeof call === "function") ? call : self;
  3301. }
  3302. function _inherits$3(subClass, superClass) {
  3303. if (typeof superClass !== "function" && superClass !== null) {
  3304. throw new TypeError("Super expression must either be null or a function, not " + (typeof superClass === 'undefined' ? 'undefined' : _typeof2(superClass)));
  3305. }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;
  3306. }
  3307. var COL_WIDTH = HEATMAP_SQUARE_SIZE$1 + HEATMAP_GUTTER_SIZE$1;
  3308. var ROW_HEIGHT = COL_WIDTH;
  3309. // const DAY_INCR = 1;
  3310. var Heatmap = function (_BaseChart) {
  3311. _inherits$3(Heatmap, _BaseChart);
  3312. function Heatmap(parent, options) {
  3313. _classCallCheck$7(this, Heatmap);
  3314. var _this = _possibleConstructorReturn$3(this, (Heatmap.__proto__ || Object.getPrototypeOf(Heatmap)).call(this, parent, options));
  3315. _this.type = 'heatmap';
  3316. _this.countLabel = options.countLabel || '';
  3317. var validStarts = ['Sunday', 'Monday'];
  3318. var startSubDomain = validStarts.includes(options.startSubDomain) ? options.startSubDomain : 'Sunday';
  3319. _this.startSubDomainIndex = validStarts.indexOf(startSubDomain);
  3320. _this.setup();
  3321. return _this;
  3322. }
  3323. _createClass$6(Heatmap, [{
  3324. key: 'setMeasures',
  3325. value: function setMeasures(options) {
  3326. var m = this.measures;
  3327. this.discreteDomains = options.discreteDomains === 0 ? 0 : 1;
  3328. m.paddings.top = ROW_HEIGHT * 3;
  3329. m.paddings.bottom = 0;
  3330. m.legendHeight = ROW_HEIGHT * 2;
  3331. m.baseHeight = ROW_HEIGHT * NO_OF_DAYS_IN_WEEK + getExtraHeight$1(m);
  3332. var d = this.data;
  3333. var spacing = this.discreteDomains ? NO_OF_YEAR_MONTHS : 0;
  3334. this.independentWidth = (getWeeksBetween(d.start, d.end) + spacing) * COL_WIDTH + getExtraWidth$1(m);
  3335. }
  3336. }, {
  3337. key: 'updateWidth',
  3338. value: function updateWidth() {
  3339. var spacing = this.discreteDomains ? NO_OF_YEAR_MONTHS : 0;
  3340. var noOfWeeks = this.state.noOfWeeks ? this.state.noOfWeeks : 52;
  3341. this.baseWidth = (noOfWeeks + spacing) * COL_WIDTH + getExtraWidth$1(this.measures);
  3342. }
  3343. }, {
  3344. key: 'prepareData',
  3345. value: function prepareData() {
  3346. var data = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : this.data;
  3347. if (data.start && data.end && data.start > data.end) {
  3348. throw new Error('Start date cannot be greater than end date.');
  3349. }
  3350. if (!data.start) {
  3351. data.start = new Date();
  3352. data.start.setFullYear(data.start.getFullYear() - 1);
  3353. }
  3354. if (!data.end) {
  3355. data.end = new Date();
  3356. }
  3357. data.dataPoints = data.dataPoints || {};
  3358. if (parseInt(Object.keys(data.dataPoints)[0]) > 100000) {
  3359. var points = {};
  3360. Object.keys(data.dataPoints).forEach(function (timestampSec$$1) {
  3361. var date = new Date(timestampSec$$1 * NO_OF_MILLIS);
  3362. points[getYyyyMmDd(date)] = data.dataPoints[timestampSec$$1];
  3363. });
  3364. data.dataPoints = points;
  3365. }
  3366. return data;
  3367. }
  3368. }, {
  3369. key: 'calc',
  3370. value: function calc() {
  3371. var s = this.state;
  3372. s.start = clone(this.data.start);
  3373. s.end = clone(this.data.end);
  3374. s.firstWeekStart = clone(s.start);
  3375. s.noOfWeeks = getWeeksBetween(s.start, s.end);
  3376. s.distribution = calcDistribution(Object.values(this.data.dataPoints), HEATMAP_DISTRIBUTION_SIZE$1);
  3377. s.domainConfigs = this.getDomains();
  3378. }
  3379. }, {
  3380. key: 'setupComponents',
  3381. value: function setupComponents() {
  3382. var _this2 = this;
  3383. var s = this.state;
  3384. var lessCol = this.discreteDomains ? 0 : 1;
  3385. var componentConfigs = s.domainConfigs.map(function (config, i) {
  3386. return ['heatDomain', {
  3387. index: config.index,
  3388. colWidth: COL_WIDTH,
  3389. rowHeight: ROW_HEIGHT,
  3390. squareSize: HEATMAP_SQUARE_SIZE$1,
  3391. xTranslate: s.domainConfigs.filter(function (config, j) {
  3392. return j < i;
  3393. }).map(function (config) {
  3394. return config.cols.length - lessCol;
  3395. }).reduce(function (a, b) {
  3396. return a + b;
  3397. }, 0) * COL_WIDTH
  3398. }, function () {
  3399. return s.domainConfigs[i];
  3400. }.bind(_this2)];
  3401. });
  3402. this.components = new Map(componentConfigs.map(function (args, i) {
  3403. var component = getComponent.apply(undefined, _toConsumableArray$3(args));
  3404. return [args[0] + '-' + i, component];
  3405. }));
  3406. var y = 0;
  3407. DAY_NAMES_SHORT.forEach(function (dayName, i) {
  3408. if ([1, 3, 5].includes(i)) {
  3409. var dayText = makeText('subdomain-name', -COL_WIDTH / 2, y, dayName, {
  3410. fontSize: HEATMAP_SQUARE_SIZE$1,
  3411. dy: 8,
  3412. textAnchor: 'end'
  3413. });
  3414. _this2.drawArea.appendChild(dayText);
  3415. }
  3416. y += ROW_HEIGHT;
  3417. });
  3418. }
  3419. }, {
  3420. key: 'update',
  3421. value: function update(data) {
  3422. if (!data) {
  3423. console.error('No data to update.');
  3424. }
  3425. this.data = this.prepareData(data);
  3426. this.draw();
  3427. this.bindTooltip();
  3428. }
  3429. }, {
  3430. key: 'bindTooltip',
  3431. value: function bindTooltip() {
  3432. var _this3 = this;
  3433. this.container.addEventListener('mousemove', function (e) {
  3434. _this3.components.forEach(function (comp) {
  3435. var daySquares = comp.store;
  3436. var daySquare = e.target;
  3437. if (daySquares.includes(daySquare)) {
  3438. var count = daySquare.getAttribute('data-value');
  3439. var dateParts = daySquare.getAttribute('data-date').split('-');
  3440. var month = getMonthName(parseInt(dateParts[1]) - 1, true);
  3441. var gOff = _this3.container.getBoundingClientRect(),
  3442. pOff = daySquare.getBoundingClientRect();
  3443. var width = parseInt(e.target.getAttribute('width'));
  3444. var x = pOff.left - gOff.left + width / 2;
  3445. var y = pOff.top - gOff.top;
  3446. var value = count + ' ' + _this3.countLabel;
  3447. var name = ' on ' + month + ' ' + dateParts[0] + ', ' + dateParts[2];
  3448. _this3.tip.setValues(x, y, { name: name, value: value, valueFirst: 1 }, []);
  3449. _this3.tip.showTip();
  3450. }
  3451. });
  3452. });
  3453. }
  3454. }, {
  3455. key: 'renderLegend',
  3456. value: function renderLegend() {
  3457. var _this4 = this;
  3458. this.legendArea.textContent = '';
  3459. var x = 0;
  3460. var y = ROW_HEIGHT;
  3461. var lessText = makeText('subdomain-name', x, y, 'Less', {
  3462. fontSize: HEATMAP_SQUARE_SIZE$1 + 1,
  3463. dy: 9
  3464. });
  3465. x = COL_WIDTH * 2 + COL_WIDTH / 2;
  3466. this.legendArea.appendChild(lessText);
  3467. this.colors.slice(0, HEATMAP_DISTRIBUTION_SIZE$1).map(function (color, i) {
  3468. var square = heatSquare('heatmap-legend-unit', x + (COL_WIDTH + 3) * i, y, HEATMAP_SQUARE_SIZE$1, color);
  3469. _this4.legendArea.appendChild(square);
  3470. });
  3471. var moreTextX = x + HEATMAP_DISTRIBUTION_SIZE$1 * (COL_WIDTH + 3) + COL_WIDTH / 4;
  3472. var moreText = makeText('subdomain-name', moreTextX, y, 'More', {
  3473. fontSize: HEATMAP_SQUARE_SIZE$1 + 1,
  3474. dy: 9
  3475. });
  3476. this.legendArea.appendChild(moreText);
  3477. }
  3478. }, {
  3479. key: 'getDomains',
  3480. value: function getDomains() {
  3481. var s = this.state;
  3482. var _ref = [s.start.getMonth(), s.start.getFullYear()],
  3483. startMonth = _ref[0],
  3484. startYear = _ref[1];
  3485. var _ref2 = [s.end.getMonth(), s.end.getFullYear()],
  3486. endMonth = _ref2[0],
  3487. endYear = _ref2[1];
  3488. var noOfMonths = endMonth - startMonth + 1 + (endYear - startYear) * 12;
  3489. var domainConfigs = [];
  3490. var startOfMonth = clone(s.start);
  3491. for (var i = 0; i < noOfMonths; i++) {
  3492. var endDate = s.end;
  3493. if (!areInSameMonth(startOfMonth, s.end)) {
  3494. var _ref3 = [startOfMonth.getMonth(), startOfMonth.getFullYear()],
  3495. month = _ref3[0],
  3496. year = _ref3[1];
  3497. endDate = getLastDateInMonth(month, year);
  3498. }
  3499. domainConfigs.push(this.getDomainConfig(startOfMonth, endDate));
  3500. addDays(endDate, 1);
  3501. startOfMonth = endDate;
  3502. }
  3503. return domainConfigs;
  3504. }
  3505. }, {
  3506. key: 'getDomainConfig',
  3507. value: function getDomainConfig(startDate) {
  3508. var endDate = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '';
  3509. var _ref4 = [startDate.getMonth(), startDate.getFullYear()],
  3510. month = _ref4[0],
  3511. year = _ref4[1];
  3512. var startOfWeek = setDayToSunday(startDate); // TODO: Monday as well
  3513. endDate = clone(endDate) || getLastDateInMonth(month, year);
  3514. var domainConfig = {
  3515. index: month,
  3516. cols: []
  3517. };
  3518. addDays(endDate, 1);
  3519. var noOfMonthWeeks = getWeeksBetween(startOfWeek, endDate);
  3520. var cols = [],
  3521. col = void 0;
  3522. for (var i = 0; i < noOfMonthWeeks; i++) {
  3523. col = this.getCol(startOfWeek, month);
  3524. cols.push(col);
  3525. startOfWeek = new Date(col[NO_OF_DAYS_IN_WEEK - 1].yyyyMmDd);
  3526. addDays(startOfWeek, 1);
  3527. }
  3528. if (col[NO_OF_DAYS_IN_WEEK - 1].dataValue !== undefined) {
  3529. addDays(startOfWeek, 1);
  3530. cols.push(this.getCol(startOfWeek, month, true));
  3531. }
  3532. domainConfig.cols = cols;
  3533. return domainConfig;
  3534. }
  3535. }, {
  3536. key: 'getCol',
  3537. value: function getCol(startDate, month) {
  3538. var empty = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
  3539. var s = this.state;
  3540. // startDate is the start of week
  3541. var currentDate = clone(startDate);
  3542. var col = [];
  3543. for (var i = 0; i < NO_OF_DAYS_IN_WEEK; i++, addDays(currentDate, 1)) {
  3544. var config = {};
  3545. // Non-generic adjustment for entire heatmap, needs state
  3546. var currentDateWithinData = currentDate >= s.start && currentDate <= s.end;
  3547. if (empty || currentDate.getMonth() !== month || !currentDateWithinData) {
  3548. config.yyyyMmDd = getYyyyMmDd(currentDate);
  3549. } else {
  3550. config = this.getSubDomainConfig(currentDate);
  3551. }
  3552. col.push(config);
  3553. }
  3554. return col;
  3555. }
  3556. }, {
  3557. key: 'getSubDomainConfig',
  3558. value: function getSubDomainConfig(date) {
  3559. var yyyyMmDd = getYyyyMmDd(date);
  3560. var dataValue = this.data.dataPoints[yyyyMmDd];
  3561. var config = {
  3562. yyyyMmDd: yyyyMmDd,
  3563. dataValue: dataValue || 0,
  3564. fill: this.colors[getMaxCheckpoint(dataValue, this.state.distribution)]
  3565. };
  3566. return config;
  3567. }
  3568. }]);
  3569. return Heatmap;
  3570. }(BaseChart);
  3571. function dataPrep(data, type) {
  3572. data.labels = data.labels || [];
  3573. var datasetLength = data.labels.length;
  3574. // Datasets
  3575. var datasets = data.datasets;
  3576. var zeroArray = new Array(datasetLength).fill(0);
  3577. if (!datasets) {
  3578. // default
  3579. datasets = [{
  3580. values: zeroArray
  3581. }];
  3582. }
  3583. var overridingType = void 0;
  3584. if (AXIS_DATASET_CHART_TYPES$1.includes(type)) {
  3585. overridingType = type;
  3586. }
  3587. datasets.map(function (d) {
  3588. // Set values
  3589. if (!d.values) {
  3590. d.values = zeroArray;
  3591. } else {
  3592. // Check for non values
  3593. var vals = d.values;
  3594. vals = vals.map(function (val) {
  3595. return !isNaN(val) ? val : 0;
  3596. });
  3597. // Trim or extend
  3598. if (vals.length > datasetLength) {
  3599. vals = vals.slice(0, datasetLength);
  3600. } else {
  3601. vals = fillArray$1(vals, datasetLength - vals.length, 0);
  3602. }
  3603. }
  3604. // Set labels
  3605. // Set type
  3606. if (overridingType) {
  3607. d.chartType = overridingType;
  3608. } else if (!d.chartType) {
  3609. d.chartType = AXIS_CHART_DEFAULT_TYPE$1;
  3610. }
  3611. });
  3612. // Markers
  3613. // Regions
  3614. // data.yRegions = data.yRegions || [];
  3615. if (data.yRegions) {
  3616. data.yRegions.map(function (d) {
  3617. if (d.end < d.start) {
  3618. var _ref = [d.end, d.start];
  3619. d.start = _ref[0];
  3620. d.end = _ref[1];
  3621. }
  3622. });
  3623. }
  3624. return data;
  3625. }
  3626. function zeroDataPrep(realData) {
  3627. var datasetLength = realData.labels.length;
  3628. var zeroArray = new Array(datasetLength).fill(0);
  3629. var zeroData = {
  3630. labels: realData.labels.slice(0, -1),
  3631. datasets: realData.datasets.map(function (d) {
  3632. return {
  3633. name: '',
  3634. values: zeroArray.slice(0, -1),
  3635. chartType: d.chartType
  3636. };
  3637. })
  3638. };
  3639. if (realData.yMarkers) {
  3640. zeroData.yMarkers = [{
  3641. value: 0,
  3642. label: ''
  3643. }];
  3644. }
  3645. if (realData.yRegions) {
  3646. zeroData.yRegions = [{
  3647. start: 0,
  3648. end: 0,
  3649. label: ''
  3650. }];
  3651. }
  3652. return zeroData;
  3653. }
  3654. function getShortenedLabels(chartWidth) {
  3655. var labels = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [];
  3656. var isSeries = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : true;
  3657. var allowedSpace = chartWidth / labels.length;
  3658. if (allowedSpace <= 0) allowedSpace = 1;
  3659. var allowedLetters = allowedSpace / DEFAULT_CHAR_WIDTH$1;
  3660. var calcLabels = labels.map(function (label, i) {
  3661. label += "";
  3662. if (label.length > allowedLetters) {
  3663. if (!isSeries) {
  3664. if (allowedLetters - 3 > 0) {
  3665. label = label.slice(0, allowedLetters - 3) + " ...";
  3666. } else {
  3667. label = label.slice(0, allowedLetters) + '..';
  3668. }
  3669. } else {
  3670. var multiple = Math.ceil(label.length / allowedLetters);
  3671. if (i % multiple !== 0) {
  3672. label = "";
  3673. }
  3674. }
  3675. }
  3676. return label;
  3677. });
  3678. return calcLabels;
  3679. }
  3680. var _createClass$7 = function () {
  3681. function defineProperties(target, props) {
  3682. for (var i = 0; i < props.length; i++) {
  3683. 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);
  3684. }
  3685. }return function (Constructor, protoProps, staticProps) {
  3686. if (protoProps) defineProperties(Constructor.prototype, protoProps);if (staticProps) defineProperties(Constructor, staticProps);return Constructor;
  3687. };
  3688. }();
  3689. var _get$3 = function get$$1(object, property, receiver) {
  3690. if (object === null) object = Function.prototype;var desc = Object.getOwnPropertyDescriptor(object, property);if (desc === undefined) {
  3691. var parent = Object.getPrototypeOf(object);if (parent === null) {
  3692. return undefined;
  3693. } else {
  3694. return get$$1(parent, property, receiver);
  3695. }
  3696. } else if ("value" in desc) {
  3697. return desc.value;
  3698. } else {
  3699. var getter = desc.get;if (getter === undefined) {
  3700. return undefined;
  3701. }return getter.call(receiver);
  3702. }
  3703. };
  3704. function _toConsumableArray$5(arr) {
  3705. if (Array.isArray(arr)) {
  3706. for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) {
  3707. arr2[i] = arr[i];
  3708. }return arr2;
  3709. } else {
  3710. return Array.from(arr);
  3711. }
  3712. }
  3713. function _classCallCheck$8(instance, Constructor) {
  3714. if (!(instance instanceof Constructor)) {
  3715. throw new TypeError("Cannot call a class as a function");
  3716. }
  3717. }
  3718. function _possibleConstructorReturn$4(self, call) {
  3719. if (!self) {
  3720. throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
  3721. }return call && ((typeof call === 'undefined' ? 'undefined' : _typeof2(call)) === "object" || typeof call === "function") ? call : self;
  3722. }
  3723. function _inherits$4(subClass, superClass) {
  3724. if (typeof superClass !== "function" && superClass !== null) {
  3725. throw new TypeError("Super expression must either be null or a function, not " + (typeof superClass === 'undefined' ? 'undefined' : _typeof2(superClass)));
  3726. }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;
  3727. }
  3728. var AxisChart = function (_BaseChart) {
  3729. _inherits$4(AxisChart, _BaseChart);
  3730. function AxisChart(parent, args) {
  3731. _classCallCheck$8(this, AxisChart);
  3732. var _this = _possibleConstructorReturn$4(this, (AxisChart.__proto__ || Object.getPrototypeOf(AxisChart)).call(this, parent, args));
  3733. _this.barOptions = args.barOptions || {};
  3734. _this.lineOptions = args.lineOptions || {};
  3735. _this.init = 1;
  3736. _this.setup();
  3737. return _this;
  3738. }
  3739. _createClass$7(AxisChart, [{
  3740. key: 'setMeasures',
  3741. value: function setMeasures() {
  3742. if (this.data.datasets.length <= 1) {
  3743. this.config.showLegend = 0;
  3744. this.measures.paddings.bottom = 30;
  3745. }
  3746. }
  3747. }, {
  3748. key: 'configure',
  3749. value: function configure(options) {
  3750. _get$3(AxisChart.prototype.__proto__ || Object.getPrototypeOf(AxisChart.prototype), 'configure', this).call(this, options);
  3751. options.axisOptions = options.axisOptions || {};
  3752. options.tooltipOptions = options.tooltipOptions || {};
  3753. this.config.xAxisMode = options.axisOptions.xAxisMode || 'span';
  3754. this.config.yAxisMode = options.axisOptions.yAxisMode || 'span';
  3755. this.config.xIsSeries = options.axisOptions.xIsSeries || 0;
  3756. this.config.formatTooltipX = options.tooltipOptions.formatTooltipX;
  3757. this.config.formatTooltipY = options.tooltipOptions.formatTooltipY;
  3758. this.config.valuesOverPoints = options.valuesOverPoints;
  3759. }
  3760. }, {
  3761. key: 'prepareData',
  3762. value: function prepareData() {
  3763. var data = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : this.data;
  3764. return dataPrep(data, this.type);
  3765. }
  3766. }, {
  3767. key: 'prepareFirstData',
  3768. value: function prepareFirstData() {
  3769. var data = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : this.data;
  3770. return zeroDataPrep(data);
  3771. }
  3772. }, {
  3773. key: 'calc',
  3774. value: function calc() {
  3775. var onlyWidthChange = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;
  3776. this.calcXPositions();
  3777. if (!onlyWidthChange) {
  3778. this.calcYAxisParameters(this.getAllYValues(), this.type === 'line');
  3779. }
  3780. this.makeDataByIndex();
  3781. }
  3782. }, {
  3783. key: 'calcXPositions',
  3784. value: function calcXPositions() {
  3785. var s = this.state;
  3786. var labels = this.data.labels;
  3787. s.datasetLength = labels.length;
  3788. s.unitWidth = this.width / s.datasetLength;
  3789. // Default, as per bar, and mixed. Only line will be a special case
  3790. s.xOffset = s.unitWidth / 2;
  3791. // // For a pure Line Chart
  3792. // s.unitWidth = this.width/(s.datasetLength - 1);
  3793. // s.xOffset = 0;
  3794. s.xAxis = {
  3795. labels: labels,
  3796. positions: labels.map(function (d, i) {
  3797. return floatTwo$1(s.xOffset + i * s.unitWidth);
  3798. })
  3799. };
  3800. }
  3801. }, {
  3802. key: 'calcYAxisParameters',
  3803. value: function calcYAxisParameters(dataValues) {
  3804. var withMinimum = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'false';
  3805. var yPts = calcChartIntervals(dataValues, withMinimum);
  3806. var scaleMultiplier = this.height / getValueRange(yPts);
  3807. var intervalHeight = getIntervalSize(yPts) * scaleMultiplier;
  3808. var zeroLine = this.height - getZeroIndex(yPts) * intervalHeight;
  3809. this.state.yAxis = {
  3810. labels: yPts,
  3811. positions: yPts.map(function (d) {
  3812. return zeroLine - d * scaleMultiplier;
  3813. }),
  3814. scaleMultiplier: scaleMultiplier,
  3815. zeroLine: zeroLine
  3816. };
  3817. // Dependent if above changes
  3818. this.calcDatasetPoints();
  3819. this.calcYExtremes();
  3820. this.calcYRegions();
  3821. }
  3822. }, {
  3823. key: 'calcDatasetPoints',
  3824. value: function calcDatasetPoints() {
  3825. var s = this.state;
  3826. var scaleAll = function scaleAll(values) {
  3827. return values.map(function (val) {
  3828. return scale(val, s.yAxis);
  3829. });
  3830. };
  3831. s.datasets = this.data.datasets.map(function (d, i) {
  3832. var values = d.values;
  3833. var cumulativeYs = d.cumulativeYs || [];
  3834. return {
  3835. name: d.name,
  3836. index: i,
  3837. chartType: d.chartType,
  3838. values: values,
  3839. yPositions: scaleAll(values),
  3840. cumulativeYs: cumulativeYs,
  3841. cumulativeYPos: scaleAll(cumulativeYs)
  3842. };
  3843. });
  3844. }
  3845. }, {
  3846. key: 'calcYExtremes',
  3847. value: function calcYExtremes() {
  3848. var s = this.state;
  3849. if (this.barOptions.stacked) {
  3850. s.yExtremes = s.datasets[s.datasets.length - 1].cumulativeYPos;
  3851. return;
  3852. }
  3853. s.yExtremes = new Array(s.datasetLength).fill(9999);
  3854. s.datasets.map(function (d) {
  3855. d.yPositions.map(function (pos, j) {
  3856. if (pos < s.yExtremes[j]) {
  3857. s.yExtremes[j] = pos;
  3858. }
  3859. });
  3860. });
  3861. }
  3862. }, {
  3863. key: 'calcYRegions',
  3864. value: function calcYRegions() {
  3865. var s = this.state;
  3866. if (this.data.yMarkers) {
  3867. this.state.yMarkers = this.data.yMarkers.map(function (d) {
  3868. d.position = scale(d.value, s.yAxis);
  3869. if (!d.options) d.options = {};
  3870. // if(!d.label.includes(':')) {
  3871. // d.label += ': ' + d.value;
  3872. // }
  3873. return d;
  3874. });
  3875. }
  3876. if (this.data.yRegions) {
  3877. this.state.yRegions = this.data.yRegions.map(function (d) {
  3878. d.startPos = scale(d.start, s.yAxis);
  3879. d.endPos = scale(d.end, s.yAxis);
  3880. if (!d.options) d.options = {};
  3881. return d;
  3882. });
  3883. }
  3884. }
  3885. }, {
  3886. key: 'getAllYValues',
  3887. value: function getAllYValues() {
  3888. var _this2 = this,
  3889. _ref;
  3890. var key = 'values';
  3891. if (this.barOptions.stacked) {
  3892. key = 'cumulativeYs';
  3893. var cumulative = new Array(this.state.datasetLength).fill(0);
  3894. this.data.datasets.map(function (d, i) {
  3895. var values = _this2.data.datasets[i].values;
  3896. d[key] = cumulative = cumulative.map(function (c, i) {
  3897. return c + values[i];
  3898. });
  3899. });
  3900. }
  3901. var allValueLists = this.data.datasets.map(function (d) {
  3902. return d[key];
  3903. });
  3904. if (this.data.yMarkers) {
  3905. allValueLists.push(this.data.yMarkers.map(function (d) {
  3906. return d.value;
  3907. }));
  3908. }
  3909. if (this.data.yRegions) {
  3910. this.data.yRegions.map(function (d) {
  3911. allValueLists.push([d.end, d.start]);
  3912. });
  3913. }
  3914. return (_ref = []).concat.apply(_ref, _toConsumableArray$5(allValueLists));
  3915. }
  3916. }, {
  3917. key: 'setupComponents',
  3918. value: function setupComponents() {
  3919. var _this3 = this;
  3920. var componentConfigs = [['yAxis', {
  3921. mode: this.config.yAxisMode,
  3922. width: this.width
  3923. // pos: 'right'
  3924. }, function () {
  3925. return this.state.yAxis;
  3926. }.bind(this)], ['xAxis', {
  3927. mode: this.config.xAxisMode,
  3928. height: this.height
  3929. // pos: 'right'
  3930. }, function () {
  3931. var s = this.state;
  3932. s.xAxis.calcLabels = getShortenedLabels(this.width, s.xAxis.labels, this.config.xIsSeries);
  3933. return s.xAxis;
  3934. }.bind(this)], ['yRegions', {
  3935. width: this.width,
  3936. pos: 'right'
  3937. }, function () {
  3938. return this.state.yRegions;
  3939. }.bind(this)]];
  3940. var barDatasets = this.state.datasets.filter(function (d) {
  3941. return d.chartType === 'bar';
  3942. });
  3943. var lineDatasets = this.state.datasets.filter(function (d) {
  3944. return d.chartType === 'line';
  3945. });
  3946. var barsConfigs = barDatasets.map(function (d) {
  3947. var index = d.index;
  3948. return ['barGraph' + '-' + d.index, {
  3949. index: index,
  3950. color: _this3.colors[index],
  3951. stacked: _this3.barOptions.stacked,
  3952. // same for all datasets
  3953. valuesOverPoints: _this3.config.valuesOverPoints,
  3954. minHeight: _this3.height * MIN_BAR_PERCENT_HEIGHT$1
  3955. }, function () {
  3956. var s = this.state;
  3957. var d = s.datasets[index];
  3958. var stacked = this.barOptions.stacked;
  3959. var spaceRatio = this.barOptions.spaceRatio || BAR_CHART_SPACE_RATIO$1;
  3960. var barsWidth = s.unitWidth / 2 * (2 - spaceRatio);
  3961. var barWidth = barsWidth / (stacked ? 1 : barDatasets.length);
  3962. var xPositions = s.xAxis.positions.map(function (x) {
  3963. return x - barsWidth / 2;
  3964. });
  3965. if (!stacked) {
  3966. xPositions = xPositions.map(function (p) {
  3967. return p + barWidth * index;
  3968. });
  3969. }
  3970. var labels = new Array(s.datasetLength).fill('');
  3971. if (this.config.valuesOverPoints) {
  3972. if (stacked && d.index === s.datasets.length - 1) {
  3973. labels = d.cumulativeYs;
  3974. } else {
  3975. labels = d.values;
  3976. }
  3977. }
  3978. var offsets = new Array(s.datasetLength).fill(0);
  3979. if (stacked) {
  3980. offsets = d.yPositions.map(function (y, j) {
  3981. return y - d.cumulativeYPos[j];
  3982. });
  3983. }
  3984. return {
  3985. xPositions: xPositions,
  3986. yPositions: d.yPositions,
  3987. offsets: offsets,
  3988. // values: d.values,
  3989. labels: labels,
  3990. zeroLine: s.yAxis.zeroLine,
  3991. barsWidth: barsWidth,
  3992. barWidth: barWidth
  3993. };
  3994. }.bind(_this3)];
  3995. });
  3996. var lineConfigs = lineDatasets.map(function (d) {
  3997. var index = d.index;
  3998. return ['lineGraph' + '-' + d.index, {
  3999. index: index,
  4000. color: _this3.colors[index],
  4001. svgDefs: _this3.svgDefs,
  4002. heatline: _this3.lineOptions.heatline,
  4003. areaFill: _this3.lineOptions.areaFill,
  4004. hideDots: _this3.lineOptions.hideDots,
  4005. hideLine: _this3.lineOptions.hideLine,
  4006. // same for all datasets
  4007. valuesOverPoints: _this3.config.valuesOverPoints
  4008. }, function () {
  4009. var s = this.state;
  4010. var d = s.datasets[index];
  4011. var minLine = s.yAxis.positions[0] < s.yAxis.zeroLine ? s.yAxis.positions[0] : s.yAxis.zeroLine;
  4012. return {
  4013. xPositions: s.xAxis.positions,
  4014. yPositions: d.yPositions,
  4015. values: d.values,
  4016. zeroLine: minLine,
  4017. radius: this.lineOptions.dotSize || LINE_CHART_DOT_SIZE$1
  4018. };
  4019. }.bind(_this3)];
  4020. });
  4021. var markerConfigs = [['yMarkers', {
  4022. width: this.width,
  4023. pos: 'right'
  4024. }, function () {
  4025. return this.state.yMarkers;
  4026. }.bind(this)]];
  4027. componentConfigs = componentConfigs.concat(barsConfigs, lineConfigs, markerConfigs);
  4028. var optionals = ['yMarkers', 'yRegions'];
  4029. this.dataUnitComponents = [];
  4030. this.components = new Map(componentConfigs.filter(function (args) {
  4031. return !optionals.includes(args[0]) || _this3.state[args[0]];
  4032. }).map(function (args) {
  4033. var component = getComponent.apply(undefined, _toConsumableArray$5(args));
  4034. if (args[0].includes('lineGraph') || args[0].includes('barGraph')) {
  4035. _this3.dataUnitComponents.push(component);
  4036. }
  4037. return [args[0], component];
  4038. }));
  4039. }
  4040. }, {
  4041. key: 'makeDataByIndex',
  4042. value: function makeDataByIndex() {
  4043. var _this4 = this;
  4044. this.dataByIndex = {};
  4045. var s = this.state;
  4046. var formatX = this.config.formatTooltipX;
  4047. var formatY = this.config.formatTooltipY;
  4048. var titles = s.xAxis.labels;
  4049. titles.map(function (label, index) {
  4050. var values = _this4.state.datasets.map(function (set$$1, i) {
  4051. var value = set$$1.values[index];
  4052. return {
  4053. title: set$$1.name,
  4054. value: value,
  4055. yPos: set$$1.yPositions[index],
  4056. color: _this4.colors[i],
  4057. formatted: formatY ? formatY(value) : value
  4058. };
  4059. });
  4060. _this4.dataByIndex[index] = {
  4061. label: label,
  4062. formattedLabel: formatX ? formatX(label) : label,
  4063. xPos: s.xAxis.positions[index],
  4064. values: values,
  4065. yExtreme: s.yExtremes[index]
  4066. };
  4067. });
  4068. }
  4069. }, {
  4070. key: 'bindTooltip',
  4071. value: function bindTooltip() {
  4072. var _this5 = this;
  4073. // NOTE: could be in tooltip itself, as it is a given functionality for its parent
  4074. this.container.addEventListener('mousemove', function (e) {
  4075. var m = _this5.measures;
  4076. var o = getOffset$1(_this5.container);
  4077. var relX = e.pageX - o.left - getLeftOffset$1(m);
  4078. var relY = e.pageY - o.top;
  4079. if (relY < _this5.height + getTopOffset$1(m) && relY > getTopOffset$1(m)) {
  4080. _this5.mapTooltipXPosition(relX);
  4081. } else {
  4082. _this5.tip.hideTip();
  4083. }
  4084. });
  4085. }
  4086. }, {
  4087. key: 'mapTooltipXPosition',
  4088. value: function mapTooltipXPosition(relX) {
  4089. var s = this.state;
  4090. if (!s.yExtremes) return;
  4091. var index = getClosestInArray(relX, s.xAxis.positions, true);
  4092. var dbi = this.dataByIndex[index];
  4093. this.tip.setValues(dbi.xPos + this.tip.offset.x, dbi.yExtreme + this.tip.offset.y, { name: dbi.formattedLabel, value: '' }, dbi.values, index);
  4094. this.tip.showTip();
  4095. }
  4096. }, {
  4097. key: 'renderLegend',
  4098. value: function renderLegend() {
  4099. var _this6 = this;
  4100. var s = this.data;
  4101. if (s.datasets.length > 1) {
  4102. this.legendArea.textContent = '';
  4103. s.datasets.map(function (d, i) {
  4104. var barWidth = AXIS_LEGEND_BAR_SIZE$1;
  4105. // let rightEndPoint = this.baseWidth - this.measures.margins.left - this.measures.margins.right;
  4106. // let multiplier = s.datasets.length - i;
  4107. var rect = legendBar(
  4108. // rightEndPoint - multiplier * barWidth, // To right align
  4109. barWidth * i, '0', barWidth, _this6.colors[i], d.name);
  4110. _this6.legendArea.appendChild(rect);
  4111. });
  4112. }
  4113. }
  4114. // Overlay
  4115. }, {
  4116. key: 'makeOverlay',
  4117. value: function makeOverlay$$1() {
  4118. var _this7 = this;
  4119. if (this.init) {
  4120. this.init = 0;
  4121. return;
  4122. }
  4123. if (this.overlayGuides) {
  4124. this.overlayGuides.forEach(function (g) {
  4125. var o = g.overlay;
  4126. o.parentNode.removeChild(o);
  4127. });
  4128. }
  4129. this.overlayGuides = this.dataUnitComponents.map(function (c) {
  4130. return {
  4131. type: c.unitType,
  4132. overlay: undefined,
  4133. units: c.units
  4134. };
  4135. });
  4136. if (this.state.currentIndex === undefined) {
  4137. this.state.currentIndex = this.state.datasetLength - 1;
  4138. }
  4139. // Render overlays
  4140. this.overlayGuides.map(function (d) {
  4141. var currentUnit = d.units[_this7.state.currentIndex];
  4142. d.overlay = makeOverlay[d.type](currentUnit);
  4143. _this7.drawArea.appendChild(d.overlay);
  4144. });
  4145. }
  4146. }, {
  4147. key: 'updateOverlayGuides',
  4148. value: function updateOverlayGuides() {
  4149. if (this.overlayGuides) {
  4150. this.overlayGuides.forEach(function (g) {
  4151. var o = g.overlay;
  4152. o.parentNode.removeChild(o);
  4153. });
  4154. }
  4155. }
  4156. }, {
  4157. key: 'bindOverlay',
  4158. value: function bindOverlay() {
  4159. var _this8 = this;
  4160. this.parent.addEventListener('data-select', function () {
  4161. _this8.updateOverlay();
  4162. });
  4163. }
  4164. }, {
  4165. key: 'bindUnits',
  4166. value: function bindUnits() {
  4167. var _this9 = this;
  4168. this.dataUnitComponents.map(function (c) {
  4169. c.units.map(function (unit) {
  4170. unit.addEventListener('click', function () {
  4171. var index = unit.getAttribute('data-point-index');
  4172. _this9.setCurrentDataPoint(index);
  4173. });
  4174. });
  4175. });
  4176. // Note: Doesn't work as tooltip is absolutely positioned
  4177. this.tip.container.addEventListener('click', function () {
  4178. var index = _this9.tip.container.getAttribute('data-point-index');
  4179. _this9.setCurrentDataPoint(index);
  4180. });
  4181. }
  4182. }, {
  4183. key: 'updateOverlay',
  4184. value: function updateOverlay$$1() {
  4185. var _this10 = this;
  4186. this.overlayGuides.map(function (d) {
  4187. var currentUnit = d.units[_this10.state.currentIndex];
  4188. updateOverlay[d.type](currentUnit, d.overlay);
  4189. });
  4190. }
  4191. }, {
  4192. key: 'onLeftArrow',
  4193. value: function onLeftArrow() {
  4194. this.setCurrentDataPoint(this.state.currentIndex - 1);
  4195. }
  4196. }, {
  4197. key: 'onRightArrow',
  4198. value: function onRightArrow() {
  4199. this.setCurrentDataPoint(this.state.currentIndex + 1);
  4200. }
  4201. }, {
  4202. key: 'getDataPoint',
  4203. value: function getDataPoint() {
  4204. var index = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : this.state.currentIndex;
  4205. var s = this.state;
  4206. var data_point = {
  4207. index: index,
  4208. label: s.xAxis.labels[index],
  4209. values: s.datasets.map(function (d) {
  4210. return d.values[index];
  4211. })
  4212. };
  4213. return data_point;
  4214. }
  4215. }, {
  4216. key: 'setCurrentDataPoint',
  4217. value: function setCurrentDataPoint(index) {
  4218. var s = this.state;
  4219. index = parseInt(index);
  4220. if (index < 0) index = 0;
  4221. if (index >= s.xAxis.labels.length) index = s.xAxis.labels.length - 1;
  4222. if (index === s.currentIndex) return;
  4223. s.currentIndex = index;
  4224. fire$1(this.parent, "data-select", this.getDataPoint());
  4225. }
  4226. // API
  4227. }, {
  4228. key: 'addDataPoint',
  4229. value: function addDataPoint(label, datasetValues) {
  4230. var index = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : this.state.datasetLength;
  4231. _get$3(AxisChart.prototype.__proto__ || Object.getPrototypeOf(AxisChart.prototype), 'addDataPoint', this).call(this, label, datasetValues, index);
  4232. this.data.labels.splice(index, 0, label);
  4233. this.data.datasets.map(function (d, i) {
  4234. d.values.splice(index, 0, datasetValues[i]);
  4235. });
  4236. this.update(this.data);
  4237. }
  4238. }, {
  4239. key: 'removeDataPoint',
  4240. value: function removeDataPoint() {
  4241. var index = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : this.state.datasetLength - 1;
  4242. if (this.data.labels.length <= 1) {
  4243. return;
  4244. }
  4245. _get$3(AxisChart.prototype.__proto__ || Object.getPrototypeOf(AxisChart.prototype), 'removeDataPoint', this).call(this, index);
  4246. this.data.labels.splice(index, 1);
  4247. this.data.datasets.map(function (d) {
  4248. d.values.splice(index, 1);
  4249. });
  4250. this.update(this.data);
  4251. }
  4252. }, {
  4253. key: 'updateDataset',
  4254. value: function updateDataset(datasetValues) {
  4255. var index = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;
  4256. this.data.datasets[index].values = datasetValues;
  4257. this.update(this.data);
  4258. }
  4259. // addDataset(dataset, index) {}
  4260. // removeDataset(index = 0) {}
  4261. }, {
  4262. key: 'updateDatasets',
  4263. value: function updateDatasets(datasets) {
  4264. this.data.datasets.map(function (d, i) {
  4265. if (datasets[i]) {
  4266. d.values = datasets[i];
  4267. }
  4268. });
  4269. this.update(this.data);
  4270. }
  4271. // updateDataPoint(dataPoint, index = 0) {}
  4272. // addDataPoint(dataPoint, index = 0) {}
  4273. // removeDataPoint(index = 0) {}
  4274. }]);
  4275. return AxisChart;
  4276. }(BaseChart);
  4277. function _classCallCheck$1$1(instance, Constructor) {
  4278. if (!(instance instanceof Constructor)) {
  4279. throw new TypeError("Cannot call a class as a function");
  4280. }
  4281. }
  4282. // import MultiAxisChart from './charts/MultiAxisChart';
  4283. var chartTypes = {
  4284. bar: AxisChart,
  4285. line: AxisChart,
  4286. // multiaxis: MultiAxisChart,
  4287. percentage: PercentageChart,
  4288. heatmap: Heatmap,
  4289. pie: PieChart
  4290. };
  4291. function getChartByType() {
  4292. var chartType = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'line';
  4293. var parent = arguments[1];
  4294. var options = arguments[2];
  4295. if (chartType === 'axis-mixed') {
  4296. options.type = 'line';
  4297. return new AxisChart(parent, options);
  4298. }
  4299. if (!chartTypes[chartType]) {
  4300. console.error("Undefined chart type: " + chartType);
  4301. return;
  4302. }
  4303. return new chartTypes[chartType](parent, options);
  4304. }
  4305. var Chart = function Chart(parent, options) {
  4306. _classCallCheck$1$1(this, Chart);
  4307. return getChartByType(options.type, parent, options);
  4308. };
  4309. // Playing around with dates
  4310. var NO_OF_MILLIS$1 = 1000;
  4311. var SEC_IN_DAY$1 = 86400;
  4312. var MONTH_NAMES_SHORT = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
  4313. function clone$1(date) {
  4314. return new Date(date.getTime());
  4315. }
  4316. function timestampSec(date) {
  4317. return date.getTime() / NO_OF_MILLIS$1;
  4318. }
  4319. function timestampToMidnight(timestamp) {
  4320. var roundAhead = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
  4321. var midnightTs = Math.floor(timestamp - timestamp % SEC_IN_DAY$1);
  4322. if (roundAhead) {
  4323. return midnightTs + SEC_IN_DAY$1;
  4324. }
  4325. return midnightTs;
  4326. }
  4327. // export function getMonthsBetween(startDate, endDate) {}
  4328. // mutates
  4329. // mutates
  4330. function addDays$1(date, numberOfDays) {
  4331. date.setDate(date.getDate() + numberOfDays);
  4332. }
  4333. // Composite Chart
  4334. // ================================================================================
  4335. var reportCountList = [152, 222, 199, 287, 534, 709, 1179, 1256, 1632, 1856, 1850];
  4336. var lineCompositeData = {
  4337. labels: ["2007", "2008", "2009", "2010", "2011", "2012", "2013", "2014", "2015", "2016", "2017"],
  4338. yMarkers: [{
  4339. label: "Average 100 reports/month",
  4340. value: 1200,
  4341. options: { labelPos: 'left' }
  4342. }],
  4343. datasets: [{
  4344. "name": "Events",
  4345. "values": reportCountList
  4346. }]
  4347. };
  4348. var fireball_5_25 = [[4, 0, 3, 1, 1, 2, 1, 1, 1, 0, 1, 1], [2, 3, 3, 2, 1, 3, 0, 1, 2, 7, 10, 4], [5, 6, 2, 4, 0, 1, 4, 3, 0, 2, 0, 1], [0, 2, 6, 2, 1, 1, 2, 3, 6, 3, 7, 8], [6, 8, 7, 7, 4, 5, 6, 5, 22, 12, 10, 11], [7, 10, 11, 7, 3, 2, 7, 7, 11, 15, 22, 20], [13, 16, 21, 18, 19, 17, 12, 17, 31, 28, 25, 29], [24, 14, 21, 14, 11, 15, 19, 21, 41, 22, 32, 18], [31, 20, 30, 22, 14, 17, 21, 35, 27, 50, 117, 24], [32, 24, 21, 27, 11, 27, 43, 37, 44, 40, 48, 32], [31, 38, 36, 26, 23, 23, 25, 29, 26, 47, 61, 50]];
  4349. var fireball_2_5 = [[22, 6, 6, 9, 7, 8, 6, 14, 19, 10, 8, 20], [11, 13, 12, 8, 9, 11, 9, 13, 10, 22, 40, 24], [20, 13, 13, 19, 13, 10, 14, 13, 20, 18, 5, 9], [7, 13, 16, 19, 12, 11, 21, 27, 27, 24, 33, 33], [38, 25, 28, 22, 31, 21, 35, 42, 37, 32, 46, 53], [50, 33, 36, 34, 35, 28, 27, 52, 58, 59, 75, 69], [54, 67, 67, 45, 66, 51, 38, 64, 90, 113, 116, 87], [84, 52, 56, 51, 55, 46, 50, 87, 114, 83, 152, 93], [73, 58, 59, 63, 56, 51, 83, 140, 103, 115, 265, 89], [106, 95, 94, 71, 77, 75, 99, 136, 129, 154, 168, 156], [81, 102, 95, 72, 58, 91, 89, 122, 124, 135, 183, 171]];
  4350. var fireballOver25 = [
  4351. // [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
  4352. [0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0], [0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0], [1, 1, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0], [0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 2], [3, 2, 1, 3, 2, 0, 2, 2, 2, 3, 0, 1], [2, 3, 5, 2, 1, 3, 0, 2, 3, 5, 1, 4], [7, 4, 6, 1, 9, 2, 2, 2, 20, 9, 4, 9], [5, 6, 1, 2, 5, 4, 5, 5, 16, 9, 14, 9], [5, 4, 7, 5, 1, 5, 3, 3, 5, 7, 22, 2], [5, 13, 11, 6, 1, 7, 9, 8, 14, 17, 16, 3], [8, 9, 8, 6, 4, 8, 5, 6, 14, 11, 21, 12]];
  4353. var barCompositeData = {
  4354. labels: MONTH_NAMES_SHORT,
  4355. datasets: [{
  4356. name: "Over 25 reports",
  4357. values: fireballOver25[9]
  4358. }, {
  4359. name: "5 to 25 reports",
  4360. values: fireball_5_25[9]
  4361. }, {
  4362. name: "2 to 5 reports",
  4363. values: fireball_2_5[9]
  4364. }]
  4365. };
  4366. // Demo Chart multitype Chart
  4367. // ================================================================================
  4368. var typeData = {
  4369. labels: ["12am-3am", "3am-6am", "6am-9am", "9am-12pm", "12pm-3pm", "3pm-6pm", "6pm-9pm", "9pm-12am"],
  4370. yMarkers: [{
  4371. label: "Marker",
  4372. value: 43,
  4373. options: { labelPos: 'left'
  4374. // type: 'dashed'
  4375. } }],
  4376. yRegions: [{
  4377. label: "Region",
  4378. start: -10,
  4379. end: 50,
  4380. options: { labelPos: 'right' }
  4381. }],
  4382. datasets: [{
  4383. name: "Some Data",
  4384. values: [18, 40, 30, 35, 8, 52, 17, -4],
  4385. axisPosition: 'right',
  4386. chartType: 'bar'
  4387. }, {
  4388. name: "Another Set",
  4389. values: [30, 50, -10, 15, 18, 32, 27, 14],
  4390. axisPosition: 'right',
  4391. chartType: 'bar'
  4392. }, {
  4393. name: "Yet Another",
  4394. values: [15, 20, -3, -15, 58, 12, -17, 37],
  4395. chartType: 'line'
  4396. }]
  4397. };
  4398. var updateDataAllLabels = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun", "Mon"];
  4399. var baseLength = 10;
  4400. var fullLength = 30;
  4401. var getRandom = function getRandom() {
  4402. return Math.floor(getRandomBias(-40, 60, 0.8, 1));
  4403. };
  4404. var updateDataAllValues = Array.from({ length: fullLength }, getRandom);
  4405. // We're gonna be shuffling this
  4406. var updateDataAllIndices = updateDataAllLabels.map(function (d, i) {
  4407. return i;
  4408. });
  4409. var getUpdateArray = function getUpdateArray(sourceArray) {
  4410. var length = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 10;
  4411. var indices = updateDataAllIndices.slice(0, length);
  4412. return indices.map(function (index) {
  4413. return sourceArray[index];
  4414. });
  4415. };
  4416. var currentLastIndex = baseLength;
  4417. function getUpdateData() {
  4418. shuffle(updateDataAllIndices);
  4419. var value = getRandom();
  4420. var start = getRandom();
  4421. var end = getRandom();
  4422. currentLastIndex = baseLength;
  4423. return {
  4424. labels: updateDataAllLabels.slice(0, baseLength),
  4425. datasets: [{
  4426. values: getUpdateArray(updateDataAllValues)
  4427. }],
  4428. yMarkers: [{
  4429. label: "Altitude",
  4430. value: value,
  4431. type: 'dashed'
  4432. }],
  4433. yRegions: [{
  4434. label: "Range",
  4435. start: start,
  4436. end: end
  4437. }]
  4438. };
  4439. }
  4440. function getAddUpdateData() {
  4441. if (currentLastIndex >= fullLength) return;
  4442. // TODO: Fix update on removal
  4443. currentLastIndex++;
  4444. var c = currentLastIndex - 1;
  4445. return [updateDataAllLabels[c], [updateDataAllValues[c]]];
  4446. // updateChart.addDataPoint(
  4447. // updateDataAllLabels[index], [updateDataAllValues[index]]
  4448. // );
  4449. }
  4450. var trendsData = {
  4451. labels: [1967, 1968, 1969, 1970, 1971, 1972, 1973, 1974, 1975, 1976, 1977, 1978, 1979, 1980, 1981, 1982, 1983, 1984, 1985, 1986, 1987, 1988, 1989, 1990, 1991, 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016],
  4452. datasets: [{
  4453. values: [132.9, 150.0, 149.4, 148.0, 94.4, 97.6, 54.1, 49.2, 22.5, 18.4, 39.3, 131.0, 220.1, 218.9, 198.9, 162.4, 91.0, 60.5, 20.6, 14.8, 33.9, 123.0, 211.1, 191.8, 203.3, 133.0, 76.1, 44.9, 25.1, 11.6, 28.9, 88.3, 136.3, 173.9, 170.4, 163.6, 99.3, 65.3, 45.8, 24.7, 12.6, 4.2, 4.8, 24.9, 80.8, 84.5, 94.0, 113.3, 69.8, 39.8]
  4454. }]
  4455. };
  4456. var moonData = {
  4457. names: ["Ganymede", "Callisto", "Io", "Europa"],
  4458. masses: [14819000, 10759000, 8931900, 4800000],
  4459. distances: [1070.412, 1882.709, 421.700, 671.034],
  4460. diameters: [5262.4, 4820.6, 3637.4, 3121.6]
  4461. };
  4462. var eventsData = {
  4463. labels: ["Ganymede", "Callisto", "Io", "Europa"],
  4464. datasets: [{
  4465. "values": moonData.distances,
  4466. "formatted": moonData.distances.map(function (d) {
  4467. return d * 1000 + " km";
  4468. })
  4469. }]
  4470. };
  4471. // const jupiterMoons = {
  4472. // 'Ganymede': {
  4473. // mass: '14819000 x 10^16 kg',
  4474. // 'semi-major-axis': '1070412 km',
  4475. // 'diameter': '5262.4 km'
  4476. // },
  4477. // 'Callisto': {
  4478. // mass: '10759000 x 10^16 kg',
  4479. // 'semi-major-axis': '1882709 km',
  4480. // 'diameter': '4820.6 km'
  4481. // },
  4482. // 'Io': {
  4483. // mass: '8931900 x 10^16 kg',
  4484. // 'semi-major-axis': '421700 km',
  4485. // 'diameter': '3637.4 km'
  4486. // },
  4487. // 'Europa': {
  4488. // mass: '4800000 x 10^16 kg',
  4489. // 'semi-major-axis': '671034 km',
  4490. // 'diameter': '3121.6 km'
  4491. // },
  4492. // };
  4493. // ================================================================================
  4494. var today = new Date();
  4495. var start = clone$1(today);
  4496. addDays$1(start, 4);
  4497. var end = clone$1(start);
  4498. start.setFullYear(start.getFullYear() - 2);
  4499. end.setFullYear(end.getFullYear() - 1);
  4500. var dataPoints = {};
  4501. var startTs = timestampSec(start);
  4502. var endTs = timestampSec(end);
  4503. startTs = timestampToMidnight(startTs);
  4504. endTs = timestampToMidnight(endTs, true);
  4505. while (startTs < endTs) {
  4506. dataPoints[parseInt(startTs)] = Math.floor(getRandomBias(0, 5, 0.2, 1));
  4507. startTs += SEC_IN_DAY$1;
  4508. }
  4509. var heatmapData = {
  4510. dataPoints: dataPoints,
  4511. start: start,
  4512. end: end
  4513. };
  4514. var lineComposite = {
  4515. config: {
  4516. title: "Fireball/Bolide Events - Yearly (reported)",
  4517. data: lineCompositeData,
  4518. type: "line",
  4519. height: 190,
  4520. colors: ["green"],
  4521. isNavigable: 1,
  4522. valuesOverPoints: 1,
  4523. lineOptions: {
  4524. dotSize: 8
  4525. }
  4526. }
  4527. };
  4528. var barComposite = {
  4529. config: {
  4530. data: barCompositeData,
  4531. type: "bar",
  4532. height: 210,
  4533. colors: ["violet", "light-blue", "#46a9f9"],
  4534. valuesOverPoints: 1,
  4535. axisOptions: {
  4536. xAxisMode: "tick"
  4537. },
  4538. barOptions: {
  4539. stacked: 1
  4540. }
  4541. }
  4542. };
  4543. var demoSections = [{
  4544. title: "Create a Chart",
  4545. name: "demo-main",
  4546. contentBlocks: [{
  4547. type: "code",
  4548. lang: "html",
  4549. content: ' &lt!--HTML--&gt;\n &lt;figure id="frost-chart"&gt;&lt;/figure&gt;'
  4550. }, {
  4551. type: "code",
  4552. lang: "javascript",
  4553. content: ' // Javascript\n let chart = new frappe.Chart( "#frost-chart", { // or DOM element\n data: {\n labels: ["12am-3am", "3am-6am", "6am-9am", "9am-12pm",\n "12pm-3pm", "3pm-6pm", "6pm-9pm", "9pm-12am"],\n\n datasets: [\n {\n name: "Some Data", chartType: \'bar\',\n values: [25, 40, 30, 35, 8, 52, 17, -4]\n },\n {\n name: "Another Set", chartType: \'bar\',\n values: [25, 50, -10, 15, 18, 32, 27, 14]\n },\n {\n name: "Yet Another", chartType: \'line\',\n values: [15, 20, -3, -15, 58, 12, -17, 37]\n }\n ],\n\n yMarkers: [{ label: "Marker", value: 70,\n options: { labelPos: \'left\' }}],\n yRegions: [{ label: "Region", start: -10, end: 50,\n options: { labelPos: \'right\' }}]\n },\n\n title: "My Awesome Chart",\n type: \'axis-mixed\', // or \'bar\', \'line\', \'pie\', \'percentage\'\n height: 300,\n colors: [\'purple\', \'#ffa3ef\', \'light-blue\'],\n\n tooltipOptions: {\n formatTooltipX: d => (d + \'\').toUpperCase(),\n formatTooltipY: d => d + \' pts\',\n }\n });\n\n chart.export();'
  4554. }, {
  4555. type: "demo",
  4556. config: {
  4557. title: "My Awesome Chart",
  4558. data: typeData,
  4559. type: "axis-mixed",
  4560. height: 300,
  4561. colors: ["purple", "magenta", "light-blue"],
  4562. maxSlices: 10,
  4563. tooltipOptions: {
  4564. formatTooltipX: function formatTooltipX(d) {
  4565. return (d + '').toUpperCase();
  4566. },
  4567. formatTooltipY: function formatTooltipY(d) {
  4568. return d + ' pts';
  4569. }
  4570. }
  4571. },
  4572. options: [{
  4573. name: "type",
  4574. path: ["type"],
  4575. type: "string",
  4576. states: {
  4577. "Mixed": 'axis-mixed',
  4578. "Line": 'line',
  4579. "Bar": 'bar',
  4580. "Pie Chart": 'pie',
  4581. "Percentage Chart": 'percentage'
  4582. },
  4583. activeState: "Mixed"
  4584. }],
  4585. actions: [{ name: "Export ...", fn: "export", args: [] }]
  4586. }]
  4587. }, {
  4588. title: "Update Values",
  4589. name: "updates-chart",
  4590. contentBlocks: [{
  4591. type: "demo",
  4592. config: {
  4593. data: getUpdateData(),
  4594. type: 'line',
  4595. height: 300,
  4596. colors: ['#ff6c03'],
  4597. lineOptions: {
  4598. areaFill: 1
  4599. }
  4600. },
  4601. actions: [{
  4602. name: "Random Data",
  4603. fn: "update",
  4604. args: [getUpdateData()]
  4605. }, {
  4606. name: "Add Value",
  4607. fn: "addDataPoint",
  4608. args: getAddUpdateData()
  4609. }, {
  4610. name: "Remove Value",
  4611. fn: "removeDataPoint",
  4612. args: []
  4613. }, {
  4614. name: "Export ...",
  4615. fn: "export",
  4616. args: []
  4617. }]
  4618. }]
  4619. }, {
  4620. title: "Plot Trends",
  4621. name: "trends-plot",
  4622. contentBlocks: [{
  4623. type: "demo",
  4624. config: {
  4625. title: "Mean Total Sunspot Count - Yearly",
  4626. data: trendsData,
  4627. type: 'line',
  4628. height: 300,
  4629. colors: ['#238e38'],
  4630. axisOptions: {
  4631. xAxisMode: 'tick',
  4632. yAxisMode: 'span',
  4633. xIsSeries: 1
  4634. }
  4635. },
  4636. options: [{
  4637. name: "lineOptions",
  4638. path: ["lineOptions"],
  4639. type: "map",
  4640. mapKeys: ['hideLine', 'hideDots', 'heatline', 'areaFill'],
  4641. states: {
  4642. "Line": [0, 1, 0, 0],
  4643. "Dots": [1, 0, 0, 0],
  4644. "HeatLine": [0, 1, 1, 0],
  4645. "Region": [0, 1, 0, 1]
  4646. },
  4647. activeState: "HeatLine"
  4648. }],
  4649. actions: [{ name: "Export ...", fn: "export", args: [] }]
  4650. }]
  4651. }, {
  4652. title: "Listen to state change",
  4653. name: "state-change",
  4654. contentBlocks: [{
  4655. type: "demo",
  4656. config: {
  4657. title: "Jupiter's Moons: Semi-major Axis (1000 km)",
  4658. data: eventsData,
  4659. type: 'bar',
  4660. height: 330,
  4661. colors: ['grey'],
  4662. isNavigable: 1
  4663. },
  4664. sideContent: '<div class="image-container border">\n <img class="moon-image" src="./assets/img/europa.jpg">\n </div>\n <div class="content-data mt1">\n <h6 class="moon-name">Europa</h6>\n <p>Semi-major-axis: <span class="semi-major-axis">671034</span> km</p>\n <p>Mass: <span class="mass">4800000</span> x 10^16 kg</p>\n <p>Diameter: <span class="diameter">3121.6</span> km</p>\n </div>',
  4665. postSetup: function postSetup(chart, figure, row) {
  4666. chart.parent.addEventListener('data-select', function (e) {
  4667. var i = e.index;
  4668. var name = moonData.names[i];
  4669. row.querySelector('.moon-name').innerHTML = name;
  4670. row.querySelector('.semi-major-axis').innerHTML = moonData.distances[i] * 1000;
  4671. row.querySelector('.mass').innerHTML = moonData.masses[i];
  4672. row.querySelector('.diameter').innerHTML = moonData.diameters[i];
  4673. row.querySelector('img').src = "./assets/img/" + name.toLowerCase() + ".jpg";
  4674. });
  4675. }
  4676. }, {
  4677. type: "code",
  4678. lang: "javascript",
  4679. content: ' ...\n isNavigable: 1, // Navigate across data points; default 0\n ...\n\n chart.parent.addEventListener(\'data-select\', (e) => {\n update_moon_data(e.index); // e contains index and value of current datapoint\n });'
  4680. }]
  4681. }, {
  4682. title: "And a Month-wise Heatmap",
  4683. name: "heatmap",
  4684. contentBlocks: [{
  4685. type: "demo",
  4686. config: {
  4687. title: "Monthly Distribution",
  4688. data: heatmapData,
  4689. type: 'heatmap',
  4690. discreteDomains: 1,
  4691. countLabel: 'Level',
  4692. colors: HEATMAP_COLORS_BLUE,
  4693. legendScale: [0, 1, 2, 4, 5]
  4694. },
  4695. options: [{
  4696. name: "Discrete domains",
  4697. path: ["discreteDomains"],
  4698. type: 'boolean',
  4699. // boolNames: ["Continuous", "Discrete"],
  4700. states: { "Discrete": 1, "Continuous": 0 }
  4701. }, {
  4702. name: "Colors",
  4703. path: ["colors"],
  4704. type: "object",
  4705. states: {
  4706. "Green (Default)": [],
  4707. "Blue": HEATMAP_COLORS_BLUE,
  4708. "GitHub's Halloween": HEATMAP_COLORS_YELLOW
  4709. }
  4710. }],
  4711. actions: [{ name: "Export ...", fn: "export", args: [] }]
  4712. }, {
  4713. type: "code",
  4714. lang: "javascript",
  4715. content: ' let heatmap = new frappe.Chart("#heatmap", {\n type: \'heatmap\',\n title: "Monthly Distribution",\n data: {\n dataPoints: {\'1524064033\': 8, /* ... */},\n // object with timestamp-value pairs\n start: startDate\n end: endDate // Date objects\n },\n countLabel: \'Level\',\n discreteDomains: 0 // default: 1\n colors: [\'#ebedf0\', \'#c0ddf9\', \'#73b3f3\', \'#3886e1\', \'#17459e\'],\n // Set of five incremental colors,\n // preferably with a low-saturation color for zero data;\n // def: [\'#ebedf0\', \'#c6e48b\', \'#7bc96f\', \'#239a3b\', \'#196127\']\n });'
  4716. }]
  4717. }, {
  4718. title: "Demo",
  4719. name: "codepen",
  4720. contentBlocks: [{
  4721. type: "custom",
  4722. html: '<p data-height="299" data-theme-id="light" data-slug-hash="wjKBoq" data-default-tab="js,result"\n data-user="pratu16x7" data-embed-version="2" data-pen-title="Frappe Charts Demo" class="codepen">\n See the Pen <a href="https://codepen.io/pratu16x7/pen/wjKBoq/">Frappe Charts Demo</a>\n by Prateeksha Singh (<a href="https://codepen.io/pratu16x7">@pratu16x7</a>) on\n <a href="https://codepen.io">CodePen</a>.\n </p>'
  4723. }]
  4724. }, {
  4725. title: "Available Options",
  4726. name: "options",
  4727. contentBlocks: [{
  4728. type: "code",
  4729. lang: "javascript",
  4730. content: '\n ...\n {\n data: {\n labels: [],\n datasets: [],\n yRegions: [],\n yMarkers: []\n }\n title: \'\',\n colors: [],\n height: 200,\n\n tooltipOptions: {\n formatTooltipX: d => (d + \'\').toUpperCase(),\n formatTooltipY: d => d + \' pts\',\n }\n\n // Axis charts\n isNavigable: 1, // default: 0\n valuesOverPoints: 1, // default: 0\n barOptions: {\n spaceRatio: 1 // default: 0.5\n stacked: 1 // default: 0\n }\n\n lineOptions: {\n dotSize: 6, // default: 4\n hideLine: 0, // default: 0\n hideDots: 1, // default: 0\n heatline: 1, // default: 0\n areaFill: 1 // default: 0\n }\n\n axisOptions: {\n yAxisMode: \'span\', // Axis lines, default\n xAxisMode: \'tick\', // No axis lines, only short ticks\n xIsSeries: 1 // Allow skipping x values for space\n // default: 0\n },\n\n // Pie/Percentage charts\n maxLegendPoints: 6, // default: 20\n maxSlices: 10, // default: 20\n\n // Percentage chart\n barOptions: {\n height: 15 // default: 20\n depth: 5 // default: 2\n }\n\n // Heatmap\n discreteDomains: 1, // default: 1\n }\n ...\n\n // Updating values\n chart.update(data);\n\n // Axis charts:\n chart.addDataPoint(label, valueFromEachDataset, index)\n chart.removeDataPoint(index)\n chart.updateDataset(datasetValues, index)\n\n // Exporting\n chart.export();\n\n // Unbind window-resize events\n chart.unbindWindowEvents();\n\n '
  4731. }]
  4732. }, {
  4733. title: "Install",
  4734. name: "installation",
  4735. contentBlocks: [{ type: "text", content: 'Install via npm' }, { type: "code", lang: "console", content: ' npm install frappe-charts' }, { type: "text", content: 'And include it in your project' }, { type: "code", lang: "javascript", content: ' import { Chart } from "frappe-charts' }, { type: "text", content: 'Use as:' }, {
  4736. type: "code",
  4737. lang: "javascript",
  4738. content: ' new Chart(); // ES6 module\n // or\n new frappe.Chart(); // Browser'
  4739. }, { type: "text", content: '... or include it directly in your HTML' }, {
  4740. type: "code",
  4741. lang: "html",
  4742. content: ' &lt;script src="https://unpkg.com/frappe-charts@1.1.0"&gt;&lt;/script&gt;'
  4743. }]
  4744. }];
  4745. var dbd = new docsBuilder(Chart);
  4746. var currentElement = document.querySelector('header');
  4747. if (document.querySelectorAll('#line-composite-1').length && !document.querySelector('#home-page').classList.contains("hide")) {
  4748. var lineCompositeChart = new Chart("#line-composite-1", lineComposite.config);
  4749. var barCompositeChart = new Chart("#bar-composite-1", barComposite.config);
  4750. lineCompositeChart.parent.addEventListener('data-select', function (e) {
  4751. var i = e.index;
  4752. barCompositeChart.updateDatasets([fireballOver25[i], fireball_5_25[i], fireball_2_5[i]]);
  4753. });
  4754. demoSections.forEach(function (sectionConf) {
  4755. var sectionEl = $.create('section', { className: sectionConf.name || sectionConf.title });
  4756. insertAfter(sectionEl, currentElement);
  4757. currentElement = sectionEl;
  4758. dbd.makeSection(sectionEl, sectionConf);
  4759. });
  4760. }
  4761. }());