Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.
 
 
 

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