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

3347 line
91 KiB

  1. var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) {
  2. return typeof obj;
  3. } : function (obj) {
  4. return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
  5. };
  6. var asyncGenerator = function () {
  7. function AwaitValue(value) {
  8. this.value = value;
  9. }
  10. function AsyncGenerator(gen) {
  11. var front, back;
  12. function send(key, arg) {
  13. return new Promise(function (resolve, reject) {
  14. var request = {
  15. key: key,
  16. arg: arg,
  17. resolve: resolve,
  18. reject: reject,
  19. next: null
  20. };
  21. if (back) {
  22. back = back.next = request;
  23. } else {
  24. front = back = request;
  25. resume(key, arg);
  26. }
  27. });
  28. }
  29. function resume(key, arg) {
  30. try {
  31. var result = gen[key](arg);
  32. var value = result.value;
  33. if (value instanceof AwaitValue) {
  34. Promise.resolve(value.value).then(function (arg) {
  35. resume("next", arg);
  36. }, function (arg) {
  37. resume("throw", arg);
  38. });
  39. } else {
  40. settle(result.done ? "return" : "normal", result.value);
  41. }
  42. } catch (err) {
  43. settle("throw", err);
  44. }
  45. }
  46. function settle(type, value) {
  47. switch (type) {
  48. case "return":
  49. front.resolve({
  50. value: value,
  51. done: true
  52. });
  53. break;
  54. case "throw":
  55. front.reject(value);
  56. break;
  57. default:
  58. front.resolve({
  59. value: value,
  60. done: false
  61. });
  62. break;
  63. }
  64. front = front.next;
  65. if (front) {
  66. resume(front.key, front.arg);
  67. } else {
  68. back = null;
  69. }
  70. }
  71. this._invoke = send;
  72. if (typeof gen.return !== "function") {
  73. this.return = undefined;
  74. }
  75. }
  76. if (typeof Symbol === "function" && Symbol.asyncIterator) {
  77. AsyncGenerator.prototype[Symbol.asyncIterator] = function () {
  78. return this;
  79. };
  80. }
  81. AsyncGenerator.prototype.next = function (arg) {
  82. return this._invoke("next", arg);
  83. };
  84. AsyncGenerator.prototype.throw = function (arg) {
  85. return this._invoke("throw", arg);
  86. };
  87. AsyncGenerator.prototype.return = function (arg) {
  88. return this._invoke("return", arg);
  89. };
  90. return {
  91. wrap: function (fn) {
  92. return function () {
  93. return new AsyncGenerator(fn.apply(this, arguments));
  94. };
  95. },
  96. await: function (value) {
  97. return new AwaitValue(value);
  98. }
  99. };
  100. }();
  101. var classCallCheck = function (instance, Constructor) {
  102. if (!(instance instanceof Constructor)) {
  103. throw new TypeError("Cannot call a class as a function");
  104. }
  105. };
  106. var createClass = function () {
  107. function defineProperties(target, props) {
  108. for (var i = 0; i < props.length; i++) {
  109. var descriptor = props[i];
  110. descriptor.enumerable = descriptor.enumerable || false;
  111. descriptor.configurable = true;
  112. if ("value" in descriptor) descriptor.writable = true;
  113. Object.defineProperty(target, descriptor.key, descriptor);
  114. }
  115. }
  116. return function (Constructor, protoProps, staticProps) {
  117. if (protoProps) defineProperties(Constructor.prototype, protoProps);
  118. if (staticProps) defineProperties(Constructor, staticProps);
  119. return Constructor;
  120. };
  121. }();
  122. var get = function get(object, property, receiver) {
  123. if (object === null) object = Function.prototype;
  124. var desc = Object.getOwnPropertyDescriptor(object, property);
  125. if (desc === undefined) {
  126. var parent = Object.getPrototypeOf(object);
  127. if (parent === null) {
  128. return undefined;
  129. } else {
  130. return get(parent, property, receiver);
  131. }
  132. } else if ("value" in desc) {
  133. return desc.value;
  134. } else {
  135. var getter = desc.get;
  136. if (getter === undefined) {
  137. return undefined;
  138. }
  139. return getter.call(receiver);
  140. }
  141. };
  142. var inherits = function (subClass, superClass) {
  143. if (typeof superClass !== "function" && superClass !== null) {
  144. throw new TypeError("Super expression must either be null or a function, not " + typeof superClass);
  145. }
  146. subClass.prototype = Object.create(superClass && superClass.prototype, {
  147. constructor: {
  148. value: subClass,
  149. enumerable: false,
  150. writable: true,
  151. configurable: true
  152. }
  153. });
  154. if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;
  155. };
  156. var possibleConstructorReturn = function (self, call) {
  157. if (!self) {
  158. throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
  159. }
  160. return call && (typeof call === "object" || typeof call === "function") ? call : self;
  161. };
  162. var slicedToArray = function () {
  163. function sliceIterator(arr, i) {
  164. var _arr = [];
  165. var _n = true;
  166. var _d = false;
  167. var _e = undefined;
  168. try {
  169. for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) {
  170. _arr.push(_s.value);
  171. if (i && _arr.length === i) break;
  172. }
  173. } catch (err) {
  174. _d = true;
  175. _e = err;
  176. } finally {
  177. try {
  178. if (!_n && _i["return"]) _i["return"]();
  179. } finally {
  180. if (_d) throw _e;
  181. }
  182. }
  183. return _arr;
  184. }
  185. return function (arr, i) {
  186. if (Array.isArray(arr)) {
  187. return arr;
  188. } else if (Symbol.iterator in Object(arr)) {
  189. return sliceIterator(arr, i);
  190. } else {
  191. throw new TypeError("Invalid attempt to destructure non-iterable instance");
  192. }
  193. };
  194. }();
  195. var toConsumableArray = function (arr) {
  196. if (Array.isArray(arr)) {
  197. for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) arr2[i] = arr[i];
  198. return arr2;
  199. } else {
  200. return Array.from(arr);
  201. }
  202. };
  203. function $(expr, con) {
  204. return typeof expr === "string" ? (con || document).querySelector(expr) : expr || null;
  205. }
  206. $.findNodeIndex = function (node) {
  207. var i = 0;
  208. while (node.previousSibling) {
  209. node = node.previousSibling;
  210. i++;
  211. }
  212. return i;
  213. };
  214. $.create = function (tag, o) {
  215. var element = document.createElement(tag);
  216. for (var i in o) {
  217. var val = o[i];
  218. if (i === "inside") {
  219. $(val).appendChild(element);
  220. } else if (i === "around") {
  221. var ref = $(val);
  222. ref.parentNode.insertBefore(element, ref);
  223. element.appendChild(ref);
  224. } else if (i === "styles") {
  225. if ((typeof val === "undefined" ? "undefined" : _typeof(val)) === "object") {
  226. Object.keys(val).map(function (prop) {
  227. element.style[prop] = val[prop];
  228. });
  229. }
  230. } else if (i in element) {
  231. element[i] = val;
  232. } else {
  233. element.setAttribute(i, val);
  234. }
  235. }
  236. return element;
  237. };
  238. $.createSVG = function (tag, o) {
  239. var element = document.createElementNS("http://www.w3.org/2000/svg", tag);
  240. for (var i in o) {
  241. var val = o[i];
  242. if (i === "inside") {
  243. $(val).appendChild(element);
  244. } else if (i === "around") {
  245. var ref = $(val);
  246. ref.parentNode.insertBefore(element, ref);
  247. element.appendChild(ref);
  248. } else {
  249. if (i === "className") {
  250. i = "class";
  251. }
  252. if (i === "innerHTML") {
  253. element['textContent'] = val;
  254. } else {
  255. element.setAttribute(i, val);
  256. }
  257. }
  258. }
  259. return element;
  260. };
  261. $.offset = function (element) {
  262. var rect = element.getBoundingClientRect();
  263. return {
  264. // https://stackoverflow.com/a/7436602/6495043
  265. // rect.top varies with scroll, so we add whatever has been
  266. // scrolled to it to get absolute distance from actual page top
  267. top: rect.top + (document.documentElement.scrollTop || document.body.scrollTop),
  268. left: rect.left + (document.documentElement.scrollLeft || document.body.scrollLeft)
  269. };
  270. };
  271. $.isElementInViewport = function (el) {
  272. // Although straightforward: https://stackoverflow.com/a/7557433/6495043
  273. var rect = el.getBoundingClientRect();
  274. return rect.top >= 0 && rect.left >= 0 && rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) && /*or $(window).height() */
  275. rect.right <= (window.innerWidth || document.documentElement.clientWidth) /*or $(window).width() */
  276. ;
  277. };
  278. $.bind = function (element, o) {
  279. if (element) {
  280. for (var event in o) {
  281. var callback = o[event];
  282. event.split(/\s+/).forEach(function (event) {
  283. element.addEventListener(event, callback);
  284. });
  285. }
  286. }
  287. };
  288. $.unbind = function (element, o) {
  289. if (element) {
  290. for (var event in o) {
  291. var callback = o[event];
  292. event.split(/\s+/).forEach(function (event) {
  293. element.removeEventListener(event, callback);
  294. });
  295. }
  296. }
  297. };
  298. $.fire = function (target, type, properties) {
  299. var evt = document.createEvent("HTMLEvents");
  300. evt.initEvent(type, true, true);
  301. for (var j in properties) {
  302. evt[j] = properties[j];
  303. }
  304. return target.dispatchEvent(evt);
  305. };
  306. var UnitRenderer = function () {
  307. var UnitRenderer = function UnitRenderer(total_height, zero_line, avg_unit_width) {
  308. this.total_height = total_height;
  309. this.zero_line = zero_line;
  310. this.avg_unit_width = avg_unit_width;
  311. };
  312. function get_bar_height_and_y_attr(y_top, zero_line, total_height) {
  313. var height = void 0,
  314. y = void 0;
  315. if (y_top <= zero_line) {
  316. height = zero_line - y_top;
  317. y = y_top;
  318. // In case of invisible bars
  319. if (height === 0) {
  320. height = total_height * 0.01;
  321. y -= height;
  322. }
  323. } else {
  324. height = y_top - zero_line;
  325. y = zero_line;
  326. // In case of invisible bars
  327. if (height === 0) {
  328. height = total_height * 0.01;
  329. }
  330. }
  331. return [height, y];
  332. }
  333. UnitRenderer.prototype = {
  334. draw_bar: function draw_bar(x, y_top, args, color, index, dataset_index, no_of_datasets) {
  335. var total_width = this.avg_unit_width - args.space_width;
  336. var start_x = x - total_width / 2;
  337. var width = total_width / no_of_datasets;
  338. var current_x = start_x + width * dataset_index;
  339. var _get_bar_height_and_y = get_bar_height_and_y_attr(y_top, this.zero_line, this.total_height),
  340. _get_bar_height_and_y2 = slicedToArray(_get_bar_height_and_y, 2),
  341. height = _get_bar_height_and_y2[0],
  342. y = _get_bar_height_and_y2[1];
  343. return $.createSVG('rect', {
  344. className: 'bar mini fill ' + color,
  345. 'data-point-index': index,
  346. x: current_x,
  347. y: y,
  348. width: width,
  349. height: height
  350. });
  351. },
  352. draw_dot: function draw_dot(x, y, args, color, index) {
  353. return $.createSVG('circle', {
  354. className: 'fill ' + color,
  355. 'data-point-index': index,
  356. cx: x,
  357. cy: y,
  358. r: args.radius
  359. });
  360. },
  361. animate_bar: function animate_bar(bar_obj, x, y_top, index, no_of_datasets) {
  362. var start = x - this.avg_unit_width / 4;
  363. var width = this.avg_unit_width / 2 / no_of_datasets;
  364. var _get_bar_height_and_y3 = get_bar_height_and_y_attr(y_top, this.zero_line, this.total_height),
  365. _get_bar_height_and_y4 = slicedToArray(_get_bar_height_and_y3, 2),
  366. height = _get_bar_height_and_y4[0],
  367. y = _get_bar_height_and_y4[1];
  368. x = start + width * index;
  369. return [bar_obj, { width: width, height: height, x: x, y: y }, 350, "easein"];
  370. // bar.animate({height: args.new_height, y: y_top}, 350, mina.easein);
  371. },
  372. animate_dot: function animate_dot(dot_obj, x, y_top) {
  373. return [dot_obj, { cx: x, cy: y_top }, 350, "easein"];
  374. // dot.animate({cy: y_top}, 350, mina.easein);
  375. }
  376. };
  377. return UnitRenderer;
  378. }();
  379. function make_x_line(height, text_start_at, point, label_class, axis_line_class, x_pos) {
  380. var line = $.createSVG('line', {
  381. x1: 0,
  382. x2: 0,
  383. y1: 0,
  384. y2: height
  385. });
  386. var text = $.createSVG('text', {
  387. className: label_class,
  388. x: 0,
  389. y: text_start_at,
  390. dy: '.71em',
  391. innerHTML: point
  392. });
  393. var x_line = $.createSVG('g', {
  394. className: 'tick ' + axis_line_class,
  395. transform: 'translate(' + x_pos + ', 0)'
  396. });
  397. x_line.appendChild(line);
  398. x_line.appendChild(text);
  399. return x_line;
  400. }
  401. function make_y_line(start_at, width, text_end_at, point, label_class, axis_line_class, y_pos) {
  402. var darker = arguments.length > 7 && arguments[7] !== undefined ? arguments[7] : false;
  403. var line_type = arguments.length > 8 && arguments[8] !== undefined ? arguments[8] : "";
  404. var line = $.createSVG('line', {
  405. className: line_type === "dashed" ? "dashed" : "",
  406. x1: start_at,
  407. x2: width,
  408. y1: 0,
  409. y2: 0
  410. });
  411. var text = $.createSVG('text', {
  412. className: label_class,
  413. x: text_end_at,
  414. y: 0,
  415. dy: '.32em',
  416. innerHTML: point + ""
  417. });
  418. var y_line = $.createSVG('g', {
  419. className: 'tick ' + axis_line_class,
  420. transform: 'translate(0, ' + y_pos + ')',
  421. 'stroke-opacity': 1
  422. });
  423. if (darker) {
  424. line.style.stroke = "rgba(27, 31, 35, 0.6)";
  425. }
  426. y_line.appendChild(line);
  427. y_line.appendChild(text);
  428. return y_line;
  429. }
  430. // Leveraging SMIL Animations
  431. var EASING = {
  432. ease: "0.25 0.1 0.25 1",
  433. linear: "0 0 1 1",
  434. // easein: "0.42 0 1 1",
  435. easein: "0.1 0.8 0.2 1",
  436. easeout: "0 0 0.58 1",
  437. easeinout: "0.42 0 0.58 1"
  438. };
  439. function animateSVG(element, props, dur) {
  440. var easing_type = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : "linear";
  441. var type = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : undefined;
  442. var old_values = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : {};
  443. var anim_element = element.cloneNode(true);
  444. var new_element = element.cloneNode(true);
  445. for (var attributeName in props) {
  446. var animate_element = void 0;
  447. if (attributeName === 'transform') {
  448. animate_element = document.createElementNS("http://www.w3.org/2000/svg", "animateTransform");
  449. } else {
  450. animate_element = document.createElementNS("http://www.w3.org/2000/svg", "animate");
  451. }
  452. var current_value = old_values[attributeName] || element.getAttribute(attributeName);
  453. var value = props[attributeName];
  454. var anim_attr = {
  455. attributeName: attributeName,
  456. from: current_value,
  457. to: value,
  458. begin: "0s",
  459. dur: dur / 1000 + "s",
  460. values: current_value + ";" + value,
  461. keySplines: EASING[easing_type],
  462. keyTimes: "0;1",
  463. calcMode: "spline",
  464. fill: 'freeze'
  465. };
  466. if (type) {
  467. anim_attr["type"] = type;
  468. }
  469. for (var i in anim_attr) {
  470. animate_element.setAttribute(i, anim_attr[i]);
  471. }
  472. anim_element.appendChild(animate_element);
  473. if (type) {
  474. new_element.setAttribute(attributeName, "translate(" + value + ")");
  475. } else {
  476. new_element.setAttribute(attributeName, value);
  477. }
  478. }
  479. return [anim_element, new_element];
  480. }
  481. function transform(element, style) {
  482. // eslint-disable-line no-unused-vars
  483. element.style.transform = style;
  484. element.style.webkitTransform = style;
  485. element.style.msTransform = style;
  486. element.style.mozTransform = style;
  487. element.style.oTransform = style;
  488. }
  489. function runSVGAnimation(svg_container, elements) {
  490. var new_elements = [];
  491. var anim_elements = [];
  492. elements.map(function (element) {
  493. var obj = element[0];
  494. var parent = obj.unit.parentNode;
  495. var anim_element = void 0,
  496. new_element = void 0;
  497. element[0] = obj.unit;
  498. var _animateSVG = animateSVG.apply(undefined, toConsumableArray(element));
  499. var _animateSVG2 = slicedToArray(_animateSVG, 2);
  500. anim_element = _animateSVG2[0];
  501. new_element = _animateSVG2[1];
  502. new_elements.push(new_element);
  503. anim_elements.push([anim_element, parent]);
  504. parent.replaceChild(anim_element, obj.unit);
  505. if (obj.array) {
  506. obj.array[obj.index] = new_element;
  507. } else {
  508. obj.object[obj.key] = new_element;
  509. }
  510. });
  511. var anim_svg = svg_container.cloneNode(true);
  512. anim_elements.map(function (anim_element, i) {
  513. anim_element[1].replaceChild(new_elements[i], anim_element[0]);
  514. elements[i][0] = new_elements[i];
  515. });
  516. return anim_svg;
  517. }
  518. function normalize(x) {
  519. // Calculates mantissa and exponent of a number
  520. // Returns normalized number and exponent
  521. // https://stackoverflow.com/q/9383593/6495043
  522. if (x === 0) {
  523. return [0, 0];
  524. }
  525. if (isNaN(x)) {
  526. return { mantissa: -6755399441055744, exponent: 972 };
  527. }
  528. var sig = x > 0 ? 1 : -1;
  529. if (!isFinite(x)) {
  530. return { mantissa: sig * 4503599627370496, exponent: 972 };
  531. }
  532. x = Math.abs(x);
  533. var exp = Math.floor(Math.log10(x));
  534. var man = x / Math.pow(10, exp);
  535. return [sig * man, exp];
  536. }
  537. function get_range_intervals(max) {
  538. var min = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;
  539. var upper_bound = Math.ceil(max);
  540. var lower_bound = Math.floor(min);
  541. var range = upper_bound - lower_bound;
  542. var no_of_parts = range;
  543. var part_size = 1;
  544. // To avoid too many partitions
  545. if (range > 5) {
  546. if (range % 2 !== 0) {
  547. upper_bound++;
  548. // Recalc range
  549. range = upper_bound - lower_bound;
  550. }
  551. no_of_parts = range / 2;
  552. part_size = 2;
  553. }
  554. // Special case: 1 and 2
  555. if (range <= 2) {
  556. no_of_parts = 4;
  557. part_size = range / no_of_parts;
  558. }
  559. // Special case: 0
  560. if (range === 0) {
  561. no_of_parts = 5;
  562. part_size = 1;
  563. }
  564. var intervals = [];
  565. for (var i = 0; i <= no_of_parts; i++) {
  566. intervals.push(lower_bound + part_size * i);
  567. }
  568. return intervals;
  569. }
  570. function get_intervals(max_value) {
  571. var min_value = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;
  572. var _normalize = normalize(max_value),
  573. _normalize2 = slicedToArray(_normalize, 2),
  574. normal_max_value = _normalize2[0],
  575. exponent = _normalize2[1];
  576. var normal_min_value = min_value ? min_value / Math.pow(10, exponent) : 0;
  577. // Allow only 7 significant digits
  578. normal_max_value = normal_max_value.toFixed(6);
  579. var intervals = get_range_intervals(normal_max_value, normal_min_value);
  580. intervals = intervals.map(function (value) {
  581. return value * Math.pow(10, exponent);
  582. });
  583. return intervals;
  584. }
  585. function calc_intervals(values) {
  586. var with_minimum = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
  587. //*** Where the magic happens ***
  588. // Calculates best-fit y intervals from given values
  589. // and returns the interval array
  590. var max_value = Math.max.apply(Math, toConsumableArray(values));
  591. var min_value = Math.min.apply(Math, toConsumableArray(values));
  592. // Exponent to be used for pretty print
  593. var exponent = 0,
  594. intervals = []; // eslint-disable-line no-unused-vars
  595. function get_positive_first_intervals(max_value, abs_min_value) {
  596. var intervals = get_intervals(max_value);
  597. var interval_size = intervals[1] - intervals[0];
  598. // Then unshift the negative values
  599. var value = 0;
  600. for (var i = 1; value < abs_min_value; i++) {
  601. value += interval_size;
  602. intervals.unshift(-1 * value);
  603. }
  604. return intervals;
  605. }
  606. // CASE I: Both non-negative
  607. if (max_value >= 0 && min_value >= 0) {
  608. exponent = normalize(max_value)[1];
  609. if (!with_minimum) {
  610. intervals = get_intervals(max_value);
  611. } else {
  612. intervals = get_intervals(max_value, min_value);
  613. }
  614. }
  615. // CASE II: Only min_value negative
  616. else if (max_value > 0 && min_value < 0) {
  617. // `with_minimum` irrelevant in this case,
  618. // We'll be handling both sides of zero separately
  619. // (both starting from zero)
  620. // Because ceil() and floor() behave differently
  621. // in those two regions
  622. var abs_min_value = Math.abs(min_value);
  623. if (max_value >= abs_min_value) {
  624. exponent = normalize(max_value)[1];
  625. intervals = get_positive_first_intervals(max_value, abs_min_value);
  626. } else {
  627. // Mirror: max_value => abs_min_value, then change sign
  628. exponent = normalize(abs_min_value)[1];
  629. var pos_intervals = get_positive_first_intervals(abs_min_value, max_value);
  630. intervals = pos_intervals.map(function (d) {
  631. return d * -1;
  632. });
  633. }
  634. }
  635. // CASE III: Both non-positive
  636. else if (max_value <= 0 && min_value <= 0) {
  637. // Mirrored Case I:
  638. // Work with positives, then reverse the sign and array
  639. var pseudo_max_value = Math.abs(min_value);
  640. var pseudo_min_value = Math.abs(max_value);
  641. exponent = normalize(pseudo_max_value)[1];
  642. if (!with_minimum) {
  643. intervals = get_intervals(pseudo_max_value);
  644. } else {
  645. intervals = get_intervals(pseudo_max_value, pseudo_min_value);
  646. }
  647. intervals = intervals.reverse().map(function (d) {
  648. return d * -1;
  649. });
  650. }
  651. return intervals;
  652. }
  653. function calc_distribution(values, distribution_size) {
  654. // Assume non-negative values,
  655. // implying distribution minimum at zero
  656. var data_max_value = Math.max.apply(Math, toConsumableArray(values));
  657. var distribution_step = 1 / (distribution_size - 1);
  658. var distribution = [];
  659. for (var i = 0; i < distribution_size; i++) {
  660. var checkpoint = data_max_value * (distribution_step * i);
  661. distribution.push(checkpoint);
  662. }
  663. return distribution;
  664. }
  665. function get_max_checkpoint(value, distribution) {
  666. return distribution.filter(function (d) {
  667. return d < value;
  668. }).length;
  669. }
  670. /**
  671. * Returns the value of a number upto 2 decimal places.
  672. * @param {Number} d Any number
  673. */
  674. function float_2(d) {
  675. return parseFloat(d.toFixed(2));
  676. }
  677. /**
  678. * Returns whether or not two given arrays are equal.
  679. * @param {Array} arr1 First array
  680. * @param {Array} arr2 Second array
  681. */
  682. function arrays_equal(arr1, arr2) {
  683. if (arr1.length !== arr2.length) return false;
  684. var are_equal = true;
  685. arr1.map(function (d, i) {
  686. if (arr2[i] !== d) are_equal = false;
  687. });
  688. return are_equal;
  689. }
  690. /**
  691. * Shuffles array in place. ES6 version
  692. * @param {Array} array An array containing the items.
  693. */
  694. /**
  695. * Returns pixel width of string.
  696. * @param {String} string
  697. * @param {Number} char_width Width of single char in pixels
  698. */
  699. function get_string_width(string, char_width) {
  700. return (string + "").length * char_width;
  701. }
  702. var SvgTip = function () {
  703. function SvgTip(_ref) {
  704. var _ref$parent = _ref.parent,
  705. parent = _ref$parent === undefined ? null : _ref$parent;
  706. classCallCheck(this, SvgTip);
  707. this.parent = parent;
  708. this.title_name = '';
  709. this.title_value = '';
  710. this.list_values = [];
  711. this.title_value_first = 0;
  712. this.x = 0;
  713. this.y = 0;
  714. this.top = 0;
  715. this.left = 0;
  716. this.setup();
  717. }
  718. createClass(SvgTip, [{
  719. key: 'setup',
  720. value: function setup() {
  721. this.make_tooltip();
  722. }
  723. }, {
  724. key: 'refresh',
  725. value: function refresh() {
  726. this.fill();
  727. this.calc_position();
  728. // this.show_tip();
  729. }
  730. }, {
  731. key: 'make_tooltip',
  732. value: function make_tooltip() {
  733. var _this = this;
  734. this.container = $.create('div', {
  735. inside: this.parent,
  736. className: 'graph-svg-tip comparison',
  737. 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>'
  738. });
  739. this.hide_tip();
  740. this.title = this.container.querySelector('.title');
  741. this.data_point_list = this.container.querySelector('.data-point-list');
  742. this.parent.addEventListener('mouseleave', function () {
  743. _this.hide_tip();
  744. });
  745. }
  746. }, {
  747. key: 'fill',
  748. value: function fill() {
  749. var _this2 = this;
  750. var title = void 0;
  751. if (this.title_value_first) {
  752. title = '<strong>' + this.title_value + '</strong>' + this.title_name;
  753. } else {
  754. title = this.title_name + '<strong>' + this.title_value + '</strong>';
  755. }
  756. this.title.innerHTML = title;
  757. this.data_point_list.innerHTML = '';
  758. this.list_values.map(function (set$$1) {
  759. var li = $.create('li', {
  760. className: 'border-top ' + (set$$1.color || 'black'),
  761. innerHTML: '<strong style="display: block;">' + (set$$1.value === 0 || set$$1.value ? set$$1.value : '') + '</strong>\n\t\t\t\t\t' + (set$$1.title ? set$$1.title : '')
  762. });
  763. _this2.data_point_list.appendChild(li);
  764. });
  765. }
  766. }, {
  767. key: 'calc_position',
  768. value: function calc_position() {
  769. var width = this.container.offsetWidth;
  770. this.top = this.y - this.container.offsetHeight;
  771. this.left = this.x - width / 2;
  772. var max_left = this.parent.offsetWidth - width;
  773. var pointer = this.container.querySelector('.svg-pointer');
  774. if (this.left < 0) {
  775. pointer.style.left = 'calc(50% - ' + -1 * this.left + 'px)';
  776. this.left = 0;
  777. } else if (this.left > max_left) {
  778. var delta = this.left - max_left;
  779. var pointer_offset = 'calc(50% + ' + delta + 'px)';
  780. pointer.style.left = pointer_offset;
  781. this.left = max_left;
  782. } else {
  783. pointer.style.left = '50%';
  784. }
  785. }
  786. }, {
  787. key: 'set_values',
  788. value: function set_values(x, y) {
  789. var title_name = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : '';
  790. var title_value = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : '';
  791. var list_values = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : [];
  792. var title_value_first = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : 0;
  793. this.title_name = title_name;
  794. this.title_value = title_value;
  795. this.list_values = list_values;
  796. this.x = x;
  797. this.y = y;
  798. this.title_value_first = title_value_first;
  799. this.refresh();
  800. }
  801. }, {
  802. key: 'hide_tip',
  803. value: function hide_tip() {
  804. this.container.style.top = '0px';
  805. this.container.style.left = '0px';
  806. this.container.style.opacity = '0';
  807. }
  808. }, {
  809. key: 'show_tip',
  810. value: function show_tip() {
  811. this.container.style.top = this.top + 'px';
  812. this.container.style.left = this.left + 'px';
  813. this.container.style.opacity = '1';
  814. }
  815. }]);
  816. return SvgTip;
  817. }();
  818. var BaseChart = function () {
  819. function BaseChart(_ref) {
  820. var _ref$height = _ref.height,
  821. height = _ref$height === undefined ? 240 : _ref$height,
  822. _ref$title = _ref.title,
  823. title = _ref$title === undefined ? '' : _ref$title,
  824. _ref$subtitle = _ref.subtitle,
  825. subtitle = _ref$subtitle === undefined ? '' : _ref$subtitle,
  826. _ref$colors = _ref.colors,
  827. colors = _ref$colors === undefined ? [] : _ref$colors,
  828. _ref$summary = _ref.summary,
  829. summary = _ref$summary === undefined ? [] : _ref$summary,
  830. _ref$is_navigable = _ref.is_navigable,
  831. is_navigable = _ref$is_navigable === undefined ? 0 : _ref$is_navigable,
  832. _ref$has_legend = _ref.has_legend,
  833. has_legend = _ref$has_legend === undefined ? 0 : _ref$has_legend,
  834. _ref$type = _ref.type,
  835. type = _ref$type === undefined ? '' : _ref$type,
  836. parent = _ref.parent,
  837. data = _ref.data;
  838. classCallCheck(this, BaseChart);
  839. this.raw_chart_args = arguments[0];
  840. this.parent = typeof parent === 'string' ? document.querySelector(parent) : parent;
  841. this.title = title;
  842. this.subtitle = subtitle;
  843. this.data = data;
  844. this.specific_values = data.specific_values || [];
  845. this.summary = summary;
  846. this.is_navigable = is_navigable;
  847. if (this.is_navigable) {
  848. this.current_index = 0;
  849. }
  850. this.has_legend = has_legend;
  851. this.colors = colors;
  852. if (!this.colors || this.data.labels && this.colors.length < this.data.labels.length) {
  853. this.colors = ['light-blue', 'blue', 'violet', 'red', 'orange', 'yellow', 'green', 'light-green', 'purple', 'magenta'];
  854. }
  855. this.chart_types = ['line', 'scatter', 'bar', 'percentage', 'heatmap', 'pie'];
  856. this.set_margins(height);
  857. }
  858. createClass(BaseChart, [{
  859. key: 'get_different_chart',
  860. value: function get_different_chart(type) {
  861. if (!this.chart_types.includes(type)) {
  862. console.error('\'' + type + '\' is not a valid chart type.');
  863. }
  864. if (type === this.type) return;
  865. // Only across compatible types
  866. var compatible_types = {
  867. bar: ['line', 'scatter', 'percentage', 'pie'],
  868. line: ['scatter', 'bar', 'percentage', 'pie'],
  869. pie: ['line', 'scatter', 'percentage', 'bar'],
  870. scatter: ['line', 'bar', 'percentage', 'pie'],
  871. percentage: ['bar', 'line', 'scatter', 'pie'],
  872. heatmap: []
  873. };
  874. if (!compatible_types[this.type].includes(type)) {
  875. console.error('\'' + this.type + '\' chart cannot be converted to a \'' + type + '\' chart.');
  876. }
  877. // Okay, this is anticlimactic
  878. // this function will need to actually be 'change_chart_type(type)'
  879. // that will update only the required elements, but for now ...
  880. return new Chart({
  881. parent: this.raw_chart_args.parent,
  882. title: this.title,
  883. data: this.raw_chart_args.data,
  884. type: type,
  885. height: this.raw_chart_args.height
  886. });
  887. }
  888. }, {
  889. key: 'set_margins',
  890. value: function set_margins(height) {
  891. this.base_height = height;
  892. this.height = height - 40;
  893. this.translate_x = 60;
  894. this.translate_y = 10;
  895. }
  896. }, {
  897. key: 'setup',
  898. value: function setup() {
  899. if (!this.parent) {
  900. console.error("No parent element to render on was provided.");
  901. return;
  902. }
  903. this.validate_and_prepare_data();
  904. this.bind_window_events();
  905. this.refresh(true);
  906. }
  907. }, {
  908. key: 'validate_and_prepare_data',
  909. value: function validate_and_prepare_data() {}
  910. }, {
  911. key: 'bind_window_events',
  912. value: function bind_window_events() {
  913. var _this = this;
  914. window.addEventListener('resize', function () {
  915. return _this.refresh();
  916. });
  917. window.addEventListener('orientationchange', function () {
  918. return _this.refresh();
  919. });
  920. }
  921. }, {
  922. key: 'refresh',
  923. value: function refresh() {
  924. var init = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;
  925. this.setup_base_values();
  926. this.set_width();
  927. this.setup_container();
  928. this.setup_components();
  929. this.setup_values();
  930. this.setup_utils();
  931. this.make_graph_components(init);
  932. this.make_tooltip();
  933. if (this.summary.length > 0) {
  934. this.show_custom_summary();
  935. } else {
  936. this.show_summary();
  937. }
  938. if (this.is_navigable) {
  939. this.setup_navigation(init);
  940. }
  941. }
  942. }, {
  943. key: 'set_width',
  944. value: function set_width() {
  945. var special_values_width = 0;
  946. var char_width = 8;
  947. this.specific_values.map(function (val) {
  948. var str_width = get_string_width(val.title + "", char_width);
  949. if (str_width > special_values_width) {
  950. special_values_width = str_width - 40;
  951. }
  952. });
  953. this.base_width = this.parent.offsetWidth - special_values_width;
  954. this.width = this.base_width - this.translate_x * 2;
  955. }
  956. }, {
  957. key: 'setup_base_values',
  958. value: function setup_base_values() {}
  959. }, {
  960. key: 'setup_container',
  961. value: function setup_container() {
  962. this.container = $.create('div', {
  963. className: 'chart-container',
  964. innerHTML: '<h6 class="title">' + this.title + '</h6>\n\t\t\t\t<h6 class="sub-title uppercase">' + this.subtitle + '</h6>\n\t\t\t\t<div class="frappe-chart graphics"></div>\n\t\t\t\t<div class="graph-stats-container"></div>'
  965. });
  966. // Chart needs a dedicated parent element
  967. this.parent.innerHTML = '';
  968. this.parent.appendChild(this.container);
  969. this.chart_wrapper = this.container.querySelector('.frappe-chart');
  970. this.stats_wrapper = this.container.querySelector('.graph-stats-container');
  971. this.make_chart_area();
  972. this.make_draw_area();
  973. }
  974. }, {
  975. key: 'make_chart_area',
  976. value: function make_chart_area() {
  977. this.svg = $.createSVG('svg', {
  978. className: 'chart',
  979. inside: this.chart_wrapper,
  980. width: this.base_width,
  981. height: this.base_height
  982. });
  983. this.svg_defs = $.createSVG('defs', {
  984. inside: this.svg
  985. });
  986. return this.svg;
  987. }
  988. }, {
  989. key: 'make_draw_area',
  990. value: function make_draw_area() {
  991. this.draw_area = $.createSVG("g", {
  992. className: this.type + '-chart',
  993. inside: this.svg,
  994. transform: 'translate(' + this.translate_x + ', ' + this.translate_y + ')'
  995. });
  996. }
  997. }, {
  998. key: 'setup_components',
  999. value: function setup_components() {}
  1000. }, {
  1001. key: 'make_tooltip',
  1002. value: function make_tooltip() {
  1003. this.tip = new SvgTip({
  1004. parent: this.chart_wrapper
  1005. });
  1006. this.bind_tooltip();
  1007. }
  1008. }, {
  1009. key: 'show_summary',
  1010. value: function show_summary() {}
  1011. }, {
  1012. key: 'show_custom_summary',
  1013. value: function show_custom_summary() {
  1014. var _this2 = this;
  1015. this.summary.map(function (d) {
  1016. var stats = $.create('div', {
  1017. className: 'stats',
  1018. innerHTML: '<span class="indicator ' + d.color + '">' + d.title + ': ' + d.value + '</span>'
  1019. });
  1020. _this2.stats_wrapper.appendChild(stats);
  1021. });
  1022. }
  1023. }, {
  1024. key: 'setup_navigation',
  1025. value: function setup_navigation() {
  1026. var _this3 = this;
  1027. var init = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;
  1028. this.make_overlay();
  1029. if (init) {
  1030. this.bind_overlay();
  1031. document.addEventListener('keydown', function (e) {
  1032. if ($.isElementInViewport(_this3.chart_wrapper)) {
  1033. e = e || window.event;
  1034. if (e.keyCode == '37') {
  1035. _this3.on_left_arrow();
  1036. } else if (e.keyCode == '39') {
  1037. _this3.on_right_arrow();
  1038. } else if (e.keyCode == '38') {
  1039. _this3.on_up_arrow();
  1040. } else if (e.keyCode == '40') {
  1041. _this3.on_down_arrow();
  1042. } else if (e.keyCode == '13') {
  1043. _this3.on_enter_key();
  1044. }
  1045. }
  1046. });
  1047. }
  1048. }
  1049. }, {
  1050. key: 'make_overlay',
  1051. value: function make_overlay() {}
  1052. }, {
  1053. key: 'bind_overlay',
  1054. value: function bind_overlay() {}
  1055. }, {
  1056. key: 'bind_units',
  1057. value: function bind_units() {}
  1058. }, {
  1059. key: 'on_left_arrow',
  1060. value: function on_left_arrow() {}
  1061. }, {
  1062. key: 'on_right_arrow',
  1063. value: function on_right_arrow() {}
  1064. }, {
  1065. key: 'on_up_arrow',
  1066. value: function on_up_arrow() {}
  1067. }, {
  1068. key: 'on_down_arrow',
  1069. value: function on_down_arrow() {}
  1070. }, {
  1071. key: 'on_enter_key',
  1072. value: function on_enter_key() {}
  1073. }, {
  1074. key: 'get_data_point',
  1075. value: function get_data_point() {
  1076. var index = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : this.current_index;
  1077. // check for length
  1078. var data_point = {
  1079. index: index
  1080. };
  1081. var y = this.y[0];
  1082. ['svg_units', 'y_tops', 'values'].map(function (key) {
  1083. var data_key = key.slice(0, key.length - 1);
  1084. data_point[data_key] = y[key][index];
  1085. });
  1086. data_point.label = this.x[index];
  1087. return data_point;
  1088. }
  1089. }, {
  1090. key: 'update_current_data_point',
  1091. value: function update_current_data_point(index) {
  1092. index = parseInt(index);
  1093. if (index < 0) index = 0;
  1094. if (index >= this.x.length) index = this.x.length - 1;
  1095. if (index === this.current_index) return;
  1096. this.current_index = index;
  1097. $.fire(this.parent, "data-select", this.get_data_point());
  1098. }
  1099. // Objects
  1100. }, {
  1101. key: 'setup_utils',
  1102. value: function setup_utils() {}
  1103. }]);
  1104. return BaseChart;
  1105. }();
  1106. var AxisChart = function (_BaseChart) {
  1107. inherits(AxisChart, _BaseChart);
  1108. function AxisChart(args) {
  1109. classCallCheck(this, AxisChart);
  1110. var _this = possibleConstructorReturn(this, (AxisChart.__proto__ || Object.getPrototypeOf(AxisChart)).call(this, args));
  1111. _this.x = _this.data.labels;
  1112. _this.y = _this.data.datasets;
  1113. _this.is_series = args.is_series;
  1114. _this.format_tooltip_y = args.format_tooltip_y;
  1115. _this.format_tooltip_x = args.format_tooltip_x;
  1116. _this.zero_line = _this.height;
  1117. _this.old_values = {};
  1118. return _this;
  1119. }
  1120. createClass(AxisChart, [{
  1121. key: 'setup_values',
  1122. value: function setup_values() {
  1123. this.data.datasets.map(function (d) {
  1124. d.values = d.values.map(function (val) {
  1125. return !isNaN(val) ? val : 0;
  1126. });
  1127. });
  1128. this.setup_x();
  1129. this.setup_y();
  1130. }
  1131. }, {
  1132. key: 'setup_x',
  1133. value: function setup_x() {
  1134. var _this2 = this;
  1135. this.set_avg_unit_width_and_x_offset();
  1136. if (this.x_axis_positions) {
  1137. this.x_old_axis_positions = this.x_axis_positions.slice();
  1138. }
  1139. this.x_axis_positions = this.x.map(function (d, i) {
  1140. return float_2(_this2.x_offset + i * _this2.avg_unit_width);
  1141. });
  1142. if (!this.x_old_axis_positions) {
  1143. this.x_old_axis_positions = this.x_axis_positions.slice();
  1144. }
  1145. }
  1146. }, {
  1147. key: 'setup_y',
  1148. value: function setup_y() {
  1149. if (this.y_axis_values) {
  1150. this.y_old_axis_values = this.y_axis_values.slice();
  1151. }
  1152. var values = this.get_all_y_values();
  1153. if (this.y_sums && this.y_sums.length > 0) {
  1154. values = values.concat(this.y_sums);
  1155. }
  1156. this.y_axis_values = calc_intervals(values, this.type === 'line');
  1157. if (!this.y_old_axis_values) {
  1158. this.y_old_axis_values = this.y_axis_values.slice();
  1159. }
  1160. var y_pts = this.y_axis_values;
  1161. var value_range = y_pts[y_pts.length - 1] - y_pts[0];
  1162. if (this.multiplier) this.old_multiplier = this.multiplier;
  1163. this.multiplier = this.height / value_range;
  1164. if (!this.old_multiplier) this.old_multiplier = this.multiplier;
  1165. var interval = y_pts[1] - y_pts[0];
  1166. var interval_height = interval * this.multiplier;
  1167. var zero_index = void 0;
  1168. if (y_pts.indexOf(0) >= 0) {
  1169. // the range has a given zero
  1170. // zero-line on the chart
  1171. zero_index = y_pts.indexOf(0);
  1172. } else if (y_pts[0] > 0) {
  1173. // Minimum value is positive
  1174. // zero-line is off the chart: below
  1175. var min = y_pts[0];
  1176. zero_index = -1 * min / interval;
  1177. } else {
  1178. // Maximum value is negative
  1179. // zero-line is off the chart: above
  1180. var max = y_pts[y_pts.length - 1];
  1181. zero_index = -1 * max / interval + (y_pts.length - 1);
  1182. }
  1183. if (this.zero_line) this.old_zero_line = this.zero_line;
  1184. this.zero_line = this.height - zero_index * interval_height;
  1185. if (!this.old_zero_line) this.old_zero_line = this.zero_line;
  1186. }
  1187. }, {
  1188. key: 'setup_components',
  1189. value: function setup_components() {
  1190. get(AxisChart.prototype.__proto__ || Object.getPrototypeOf(AxisChart.prototype), 'setup_components', this).call(this);
  1191. this.setup_marker_components();
  1192. this.setup_aggregation_components();
  1193. this.setup_graph_components();
  1194. }
  1195. }, {
  1196. key: 'setup_marker_components',
  1197. value: function setup_marker_components() {
  1198. this.y_axis_group = $.createSVG('g', { className: 'y axis', inside: this.draw_area });
  1199. this.x_axis_group = $.createSVG('g', { className: 'x axis', inside: this.draw_area });
  1200. this.specific_y_group = $.createSVG('g', { className: 'specific axis', inside: this.draw_area });
  1201. }
  1202. }, {
  1203. key: 'setup_aggregation_components',
  1204. value: function setup_aggregation_components() {
  1205. this.sum_group = $.createSVG('g', { className: 'data-points', inside: this.draw_area });
  1206. this.average_group = $.createSVG('g', { className: 'chart-area', inside: this.draw_area });
  1207. }
  1208. }, {
  1209. key: 'setup_graph_components',
  1210. value: function setup_graph_components() {
  1211. var _this3 = this;
  1212. this.svg_units_groups = [];
  1213. this.y.map(function (d, i) {
  1214. _this3.svg_units_groups[i] = $.createSVG('g', {
  1215. className: 'data-points data-points-' + i,
  1216. inside: _this3.draw_area
  1217. });
  1218. });
  1219. }
  1220. }, {
  1221. key: 'make_graph_components',
  1222. value: function make_graph_components() {
  1223. var init = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;
  1224. this.make_y_axis();
  1225. this.make_x_axis();
  1226. this.draw_graph(init);
  1227. this.make_y_specifics();
  1228. }
  1229. // make VERTICAL lines for x values
  1230. }, {
  1231. key: 'make_x_axis',
  1232. value: function make_x_axis() {
  1233. var _this4 = this;
  1234. var animate = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;
  1235. var char_width = 8;
  1236. var start_at = void 0,
  1237. height = void 0,
  1238. text_start_at = void 0,
  1239. axis_line_class = '';
  1240. if (this.x_axis_mode === 'span') {
  1241. // long spanning lines
  1242. start_at = -7;
  1243. height = this.height + 15;
  1244. text_start_at = this.height + 25;
  1245. } else if (this.x_axis_mode === 'tick') {
  1246. // short label lines
  1247. start_at = this.height;
  1248. height = 6;
  1249. text_start_at = 9;
  1250. axis_line_class = 'x-axis-label';
  1251. }
  1252. this.x_axis_group.setAttribute('transform', 'translate(0,' + start_at + ')');
  1253. if (animate) {
  1254. this.make_anim_x_axis(height, text_start_at, axis_line_class);
  1255. return;
  1256. }
  1257. var allowed_space = this.avg_unit_width * 1.5;
  1258. var allowed_letters = allowed_space / 8;
  1259. this.x_axis_group.textContent = '';
  1260. this.x.map(function (point, i) {
  1261. var space_taken = get_string_width(point, char_width) + 2;
  1262. if (space_taken > allowed_space) {
  1263. if (_this4.is_series) {
  1264. // Skip some axis lines if X axis is a series
  1265. var skips = 1;
  1266. while (space_taken / skips * 2 > allowed_space) {
  1267. skips++;
  1268. }
  1269. if (i % skips !== 0) {
  1270. return;
  1271. }
  1272. } else {
  1273. point = point.slice(0, allowed_letters - 3) + " ...";
  1274. }
  1275. }
  1276. _this4.x_axis_group.appendChild(make_x_line(height, text_start_at, point, 'x-value-text', axis_line_class, _this4.x_axis_positions[i]));
  1277. });
  1278. }
  1279. // make HORIZONTAL lines for y values
  1280. }, {
  1281. key: 'make_y_axis',
  1282. value: function make_y_axis() {
  1283. var _this5 = this;
  1284. var animate = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;
  1285. if (animate) {
  1286. this.make_anim_y_axis();
  1287. this.make_anim_y_specifics();
  1288. return;
  1289. }
  1290. var _get_y_axis_line_prop = this.get_y_axis_line_props(),
  1291. _get_y_axis_line_prop2 = slicedToArray(_get_y_axis_line_prop, 4),
  1292. width = _get_y_axis_line_prop2[0],
  1293. text_end_at = _get_y_axis_line_prop2[1],
  1294. axis_line_class = _get_y_axis_line_prop2[2],
  1295. start_at = _get_y_axis_line_prop2[3];
  1296. this.y_axis_group.textContent = '';
  1297. this.y_axis_values.map(function (value, i) {
  1298. _this5.y_axis_group.appendChild(make_y_line(start_at, width, text_end_at, value, 'y-value-text', axis_line_class, _this5.zero_line - value * _this5.multiplier, value === 0 && i !== 0 // Non-first Zero line
  1299. ));
  1300. });
  1301. }
  1302. }, {
  1303. key: 'get_y_axis_line_props',
  1304. value: function get_y_axis_line_props() {
  1305. var specific = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;
  1306. if (specific) {
  1307. return [this.width, this.width + 5, 'specific-value', 0];
  1308. }
  1309. var width = void 0,
  1310. text_end_at = -9,
  1311. axis_line_class = '',
  1312. start_at = 0;
  1313. if (this.y_axis_mode === 'span') {
  1314. // long spanning lines
  1315. width = this.width + 6;
  1316. start_at = -6;
  1317. } else if (this.y_axis_mode === 'tick') {
  1318. // short label lines
  1319. width = -6;
  1320. axis_line_class = 'y-axis-label';
  1321. }
  1322. return [width, text_end_at, axis_line_class, start_at];
  1323. }
  1324. }, {
  1325. key: 'draw_graph',
  1326. value: function draw_graph() {
  1327. var _this6 = this;
  1328. var init = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;
  1329. if (this.raw_chart_args.hasOwnProperty("init") && !this.raw_chart_args.init) {
  1330. this.y.map(function (d, i) {
  1331. d.svg_units = [];
  1332. _this6.make_path && _this6.make_path(d, i, _this6.x_axis_positions, d.y_tops, d.color || _this6.colors[i]);
  1333. _this6.make_new_units(d, i);
  1334. _this6.calc_y_dependencies();
  1335. });
  1336. return;
  1337. }
  1338. if (init) {
  1339. this.draw_new_graph_and_animate();
  1340. return;
  1341. }
  1342. this.y.map(function (d, i) {
  1343. d.svg_units = [];
  1344. _this6.make_path && _this6.make_path(d, i, _this6.x_axis_positions, d.y_tops, d.color || _this6.colors[i]);
  1345. _this6.make_new_units(d, i);
  1346. });
  1347. }
  1348. }, {
  1349. key: 'draw_new_graph_and_animate',
  1350. value: function draw_new_graph_and_animate() {
  1351. var _this7 = this;
  1352. var data = [];
  1353. this.y.map(function (d, i) {
  1354. // Anim: Don't draw initial values, store them and update later
  1355. d.y_tops = new Array(d.values.length).fill(_this7.zero_line); // no value
  1356. data.push({ values: d.values });
  1357. d.svg_units = [];
  1358. _this7.make_path && _this7.make_path(d, i, _this7.x_axis_positions, d.y_tops, d.color || _this7.colors[i]);
  1359. _this7.make_new_units(d, i);
  1360. });
  1361. setTimeout(function () {
  1362. _this7.update_values(data);
  1363. }, 350);
  1364. }
  1365. }, {
  1366. key: 'setup_navigation',
  1367. value: function setup_navigation(init) {
  1368. var _this8 = this;
  1369. if (init) {
  1370. // Hack: defer nav till initial update_values
  1371. setTimeout(function () {
  1372. get(AxisChart.prototype.__proto__ || Object.getPrototypeOf(AxisChart.prototype), 'setup_navigation', _this8).call(_this8, init);
  1373. }, 500);
  1374. } else {
  1375. get(AxisChart.prototype.__proto__ || Object.getPrototypeOf(AxisChart.prototype), 'setup_navigation', this).call(this, init);
  1376. }
  1377. }
  1378. }, {
  1379. key: 'make_new_units',
  1380. value: function make_new_units(d, i) {
  1381. this.make_new_units_for_dataset(this.x_axis_positions, d.y_tops, d.color || this.colors[i], i, this.y.length);
  1382. }
  1383. }, {
  1384. key: 'make_new_units_for_dataset',
  1385. value: function make_new_units_for_dataset(x_values, y_values, color, dataset_index, no_of_datasets, units_group, units_array, unit) {
  1386. if (!units_group) units_group = this.svg_units_groups[dataset_index];
  1387. if (!units_array) units_array = this.y[dataset_index].svg_units;
  1388. if (!unit) unit = this.unit_args;
  1389. units_group.textContent = '';
  1390. units_array.length = 0;
  1391. var unit_renderer = new UnitRenderer(this.height, this.zero_line, this.avg_unit_width);
  1392. y_values.map(function (y, i) {
  1393. var data_unit = unit_renderer['draw_' + unit.type](x_values[i], y, unit.args, color, i, dataset_index, no_of_datasets);
  1394. units_group.appendChild(data_unit);
  1395. units_array.push(data_unit);
  1396. });
  1397. if (this.is_navigable) {
  1398. this.bind_units(units_array);
  1399. }
  1400. }
  1401. }, {
  1402. key: 'make_y_specifics',
  1403. value: function make_y_specifics() {
  1404. var _this9 = this;
  1405. this.specific_y_group.textContent = '';
  1406. this.specific_values.map(function (d) {
  1407. _this9.specific_y_group.appendChild(make_y_line(0, _this9.width, _this9.width + 5, d.title.toUpperCase(), 'specific-value', 'specific-value', _this9.zero_line - d.value * _this9.multiplier, false, d.line_type));
  1408. });
  1409. }
  1410. }, {
  1411. key: 'bind_tooltip',
  1412. value: function bind_tooltip() {
  1413. var _this10 = this;
  1414. // TODO: could be in tooltip itself, as it is a given functionality for its parent
  1415. this.chart_wrapper.addEventListener('mousemove', function (e) {
  1416. var offset = $.offset(_this10.chart_wrapper);
  1417. var relX = e.pageX - offset.left - _this10.translate_x;
  1418. var relY = e.pageY - offset.top - _this10.translate_y;
  1419. if (relY < _this10.height + _this10.translate_y * 2) {
  1420. _this10.map_tooltip_x_position_and_show(relX);
  1421. } else {
  1422. _this10.tip.hide_tip();
  1423. }
  1424. });
  1425. }
  1426. }, {
  1427. key: 'map_tooltip_x_position_and_show',
  1428. value: function map_tooltip_x_position_and_show(relX) {
  1429. var _this11 = this;
  1430. if (!this.y_min_tops) return;
  1431. var titles = this.x;
  1432. if (this.format_tooltip_x && this.format_tooltip_x(this.x[0])) {
  1433. titles = this.x.map(function (d) {
  1434. return _this11.format_tooltip_x(d);
  1435. });
  1436. }
  1437. var y_format = this.format_tooltip_y && this.format_tooltip_y(this.y[0].values[0]);
  1438. for (var i = this.x_axis_positions.length - 1; i >= 0; i--) {
  1439. var x_val = this.x_axis_positions[i];
  1440. // let delta = i === 0 ? this.avg_unit_width : x_val - this.x_axis_positions[i-1];
  1441. if (relX > x_val - this.avg_unit_width / 2) {
  1442. var x = x_val + this.translate_x;
  1443. var y = this.y_min_tops[i] + this.translate_y;
  1444. var title = titles[i];
  1445. var values = this.y.map(function (set$$1, j) {
  1446. return {
  1447. title: set$$1.title,
  1448. value: y_format ? _this11.format_tooltip_y(set$$1.values[i]) : set$$1.values[i],
  1449. color: set$$1.color || _this11.colors[j]
  1450. };
  1451. });
  1452. this.tip.set_values(x, y, title, '', values);
  1453. this.tip.show_tip();
  1454. break;
  1455. }
  1456. }
  1457. }
  1458. // API
  1459. }, {
  1460. key: 'show_sums',
  1461. value: function show_sums() {
  1462. var _this12 = this;
  1463. this.updating = true;
  1464. this.y_sums = new Array(this.x_axis_positions.length).fill(0);
  1465. this.y.map(function (d) {
  1466. d.values.map(function (value, i) {
  1467. _this12.y_sums[i] += value;
  1468. });
  1469. });
  1470. // Remake y axis, animate
  1471. this.update_values();
  1472. // Then make sum units, don't animate
  1473. this.sum_units = [];
  1474. this.make_new_units_for_dataset(this.x_axis_positions, this.y_sums.map(function (val) {
  1475. return float_2(_this12.zero_line - val * _this12.multiplier);
  1476. }), 'light-grey', 0, 1, this.sum_group, this.sum_units);
  1477. // this.make_path && this.make_path(d, i, old_x, old_y, d.color || this.colors[i]);
  1478. this.updating = false;
  1479. }
  1480. }, {
  1481. key: 'hide_sums',
  1482. value: function hide_sums() {
  1483. if (this.updating) return;
  1484. this.y_sums = [];
  1485. this.sum_group.textContent = '';
  1486. this.sum_units = [];
  1487. this.update_values();
  1488. }
  1489. }, {
  1490. key: 'show_averages',
  1491. value: function show_averages() {
  1492. var _this13 = this;
  1493. this.old_specific_values = this.specific_values.slice();
  1494. this.y.map(function (d, i) {
  1495. var sum = 0;
  1496. d.values.map(function (e) {
  1497. sum += e;
  1498. });
  1499. var average = sum / d.values.length;
  1500. _this13.specific_values.push({
  1501. title: "AVG" + " " + (i + 1),
  1502. line_type: "dashed",
  1503. value: average,
  1504. auto: 1
  1505. });
  1506. });
  1507. this.update_values();
  1508. }
  1509. }, {
  1510. key: 'hide_averages',
  1511. value: function hide_averages() {
  1512. var _this14 = this;
  1513. this.old_specific_values = this.specific_values.slice();
  1514. var indices_to_remove = [];
  1515. this.specific_values.map(function (d, i) {
  1516. if (d.auto) indices_to_remove.unshift(i);
  1517. });
  1518. indices_to_remove.map(function (index) {
  1519. _this14.specific_values.splice(index, 1);
  1520. });
  1521. this.update_values();
  1522. }
  1523. }, {
  1524. key: 'update_values',
  1525. value: function update_values(new_y, new_x) {
  1526. var _this15 = this;
  1527. if (!new_x) {
  1528. new_x = this.x;
  1529. }
  1530. this.elements_to_animate = [];
  1531. this.updating = true;
  1532. this.old_x_values = this.x.slice();
  1533. this.old_y_axis_tops = this.y.map(function (d) {
  1534. return d.y_tops.slice();
  1535. });
  1536. this.old_y_values = this.y.map(function (d) {
  1537. return d.values;
  1538. });
  1539. this.no_of_extra_pts = new_x.length - this.x.length;
  1540. // Just update values prop, setup_x/y() will do the rest
  1541. if (new_y) this.y.map(function (d, i) {
  1542. d.values = new_y[i].values;
  1543. });
  1544. if (new_x) this.x = new_x;
  1545. this.setup_x();
  1546. this.setup_y();
  1547. // Animate only if positions have changed
  1548. if (!arrays_equal(this.x_old_axis_positions, this.x_axis_positions)) {
  1549. this.make_x_axis(true);
  1550. setTimeout(function () {
  1551. if (!_this15.updating) _this15.make_x_axis();
  1552. }, 350);
  1553. }
  1554. if (!arrays_equal(this.y_old_axis_values, this.y_axis_values) || this.old_specific_values && !arrays_equal(this.old_specific_values, this.specific_values)) {
  1555. this.make_y_axis(true);
  1556. setTimeout(function () {
  1557. if (!_this15.updating) {
  1558. _this15.make_y_axis();
  1559. _this15.make_y_specifics();
  1560. }
  1561. }, 350);
  1562. }
  1563. // Change in data, so calculate dependencies
  1564. this.calc_y_dependencies();
  1565. this.animate_graphs();
  1566. // Trigger animation with the animatable elements in this.elements_to_animate
  1567. this.run_animation();
  1568. this.updating = false;
  1569. }
  1570. }, {
  1571. key: 'add_data_point',
  1572. value: function add_data_point(y_point, x_point) {
  1573. var index = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : this.x.length;
  1574. var new_y = this.y.map(function (data_set) {
  1575. return { values: data_set.values };
  1576. });
  1577. new_y.map(function (d, i) {
  1578. d.values.splice(index, 0, y_point[i]);
  1579. });
  1580. var new_x = this.x.slice();
  1581. new_x.splice(index, 0, x_point);
  1582. this.update_values(new_y, new_x);
  1583. }
  1584. }, {
  1585. key: 'remove_data_point',
  1586. value: function remove_data_point() {
  1587. var index = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : this.x.length - 1;
  1588. if (this.x.length < 3) return;
  1589. var new_y = this.y.map(function (data_set) {
  1590. return { values: data_set.values };
  1591. });
  1592. new_y.map(function (d) {
  1593. d.values.splice(index, 1);
  1594. });
  1595. var new_x = this.x.slice();
  1596. new_x.splice(index, 1);
  1597. this.update_values(new_y, new_x);
  1598. }
  1599. }, {
  1600. key: 'run_animation',
  1601. value: function run_animation() {
  1602. var _this16 = this;
  1603. var anim_svg = runSVGAnimation(this.svg, this.elements_to_animate);
  1604. if (this.svg.parentNode == this.chart_wrapper) {
  1605. this.chart_wrapper.removeChild(this.svg);
  1606. this.chart_wrapper.appendChild(anim_svg);
  1607. }
  1608. // Replace the new svg (data has long been replaced)
  1609. setTimeout(function () {
  1610. if (anim_svg.parentNode == _this16.chart_wrapper) {
  1611. _this16.chart_wrapper.removeChild(anim_svg);
  1612. _this16.chart_wrapper.appendChild(_this16.svg);
  1613. }
  1614. }, 250);
  1615. }
  1616. }, {
  1617. key: 'animate_graphs',
  1618. value: function animate_graphs() {
  1619. var _this17 = this;
  1620. this.y.map(function (d, i) {
  1621. // Pre-prep, equilize no of positions between old and new
  1622. var _calc_old_and_new_pos = _this17.calc_old_and_new_postions(d, i),
  1623. _calc_old_and_new_pos2 = slicedToArray(_calc_old_and_new_pos, 4),
  1624. old_x = _calc_old_and_new_pos2[0],
  1625. old_y = _calc_old_and_new_pos2[1],
  1626. new_x = _calc_old_and_new_pos2[2],
  1627. new_y = _calc_old_and_new_pos2[3];
  1628. if (_this17.no_of_extra_pts >= 0) {
  1629. _this17.make_path && _this17.make_path(d, i, old_x, old_y, d.color || _this17.colors[i]);
  1630. _this17.make_new_units_for_dataset(old_x, old_y, d.color || _this17.colors[i], i, _this17.y.length);
  1631. }
  1632. d.path && _this17.animate_path(d, i, old_x, old_y, new_x, new_y);
  1633. _this17.animate_units(d, i, old_x, old_y, new_x, new_y);
  1634. });
  1635. // TODO: replace with real units
  1636. setTimeout(function () {
  1637. _this17.y.map(function (d, i) {
  1638. _this17.make_path && _this17.make_path(d, i, _this17.x_axis_positions, d.y_tops, d.color || _this17.colors[i]);
  1639. _this17.make_new_units(d, i);
  1640. });
  1641. }, 400);
  1642. }
  1643. }, {
  1644. key: 'animate_path',
  1645. value: function animate_path(d, i, old_x, old_y, new_x, new_y) {
  1646. // Animate path
  1647. var new_points_list = new_y.map(function (y, i) {
  1648. return new_x[i] + ',' + y;
  1649. });
  1650. var new_path_str = new_points_list.join("L");
  1651. var path_args = [{ unit: d.path, object: d, key: 'path' }, { d: "M" + new_path_str }, 350, "easein"];
  1652. this.elements_to_animate.push(path_args);
  1653. // Animate region
  1654. if (d.region_path) {
  1655. var reg_start_pt = '0,' + this.zero_line + 'L';
  1656. var reg_end_pt = 'L' + this.width + ',' + this.zero_line;
  1657. var region_args = [{ unit: d.region_path, object: d, key: 'region_path' }, { d: "M" + reg_start_pt + new_path_str + reg_end_pt }, 350, "easein"];
  1658. this.elements_to_animate.push(region_args);
  1659. }
  1660. }
  1661. }, {
  1662. key: 'animate_units',
  1663. value: function animate_units(d, index, old_x, old_y, new_x, new_y) {
  1664. var _this18 = this;
  1665. var type = this.unit_args.type;
  1666. var unit_renderer = new UnitRenderer(this.height, this.zero_line, this.avg_unit_width);
  1667. d.svg_units.map(function (unit, i) {
  1668. if (new_x[i] === undefined || new_y[i] === undefined) return;
  1669. _this18.elements_to_animate.push(unit_renderer['animate_' + type]({ unit: unit, array: d.svg_units, index: i }, // unit, with info to replace where it came from in the data
  1670. new_x[i], new_y[i], index, _this18.y.length));
  1671. });
  1672. }
  1673. }, {
  1674. key: 'calc_old_and_new_postions',
  1675. value: function calc_old_and_new_postions(d, i) {
  1676. var old_x = this.x_old_axis_positions.slice();
  1677. var new_x = this.x_axis_positions.slice();
  1678. var old_y = this.old_y_axis_tops[i].slice();
  1679. var new_y = d.y_tops.slice();
  1680. var last_old_x_pos = old_x[old_x.length - 1];
  1681. var last_old_y_pos = old_y[old_y.length - 1];
  1682. var last_new_x_pos = new_x[new_x.length - 1];
  1683. var last_new_y_pos = new_y[new_y.length - 1];
  1684. if (this.no_of_extra_pts >= 0) {
  1685. // First substitute current path with a squiggled one (looking the same but
  1686. // having more points at end),
  1687. // then animate to stretch it later to new points
  1688. // (new points already have more points)
  1689. // Hence, the extra end points will correspond to current(old) positions
  1690. var filler_x = new Array(Math.abs(this.no_of_extra_pts)).fill(last_old_x_pos);
  1691. var filler_y = new Array(Math.abs(this.no_of_extra_pts)).fill(last_old_y_pos);
  1692. old_x = old_x.concat(filler_x);
  1693. old_y = old_y.concat(filler_y);
  1694. } else {
  1695. // Just modify the new points to have extra points
  1696. // with the same position at end
  1697. var _filler_x = new Array(Math.abs(this.no_of_extra_pts)).fill(last_new_x_pos);
  1698. var _filler_y = new Array(Math.abs(this.no_of_extra_pts)).fill(last_new_y_pos);
  1699. new_x = new_x.concat(_filler_x);
  1700. new_y = new_y.concat(_filler_y);
  1701. }
  1702. return [old_x, old_y, new_x, new_y];
  1703. }
  1704. }, {
  1705. key: 'make_anim_x_axis',
  1706. value: function make_anim_x_axis(height, text_start_at, axis_line_class) {
  1707. var _this19 = this;
  1708. // Animate X AXIS to account for more or less axis lines
  1709. var old_pos = this.x_old_axis_positions;
  1710. var new_pos = this.x_axis_positions;
  1711. var old_vals = this.old_x_values;
  1712. var new_vals = this.x;
  1713. var last_line_pos = old_pos[old_pos.length - 1];
  1714. var add_and_animate_line = function add_and_animate_line(value, old_pos, new_pos) {
  1715. if (typeof new_pos === 'string') {
  1716. new_pos = parseInt(new_pos.substring(0, new_pos.length - 1));
  1717. }
  1718. var x_line = make_x_line(height, text_start_at, value, // new value
  1719. 'x-value-text', axis_line_class, old_pos // old position
  1720. );
  1721. _this19.x_axis_group.appendChild(x_line);
  1722. _this19.elements_to_animate && _this19.elements_to_animate.push([{ unit: x_line, array: [0], index: 0 }, { transform: new_pos + ', 0' }, 350, "easein", "translate", { transform: old_pos + ', 0' }]);
  1723. };
  1724. this.x_axis_group.textContent = '';
  1725. this.make_new_axis_anim_lines(old_pos, new_pos, old_vals, new_vals, last_line_pos, add_and_animate_line);
  1726. }
  1727. }, {
  1728. key: 'make_anim_y_axis',
  1729. value: function make_anim_y_axis() {
  1730. var _this20 = this;
  1731. // Animate Y AXIS to account for more or less axis lines
  1732. var old_pos = this.y_old_axis_values.map(function (value) {
  1733. return _this20.zero_line - value * _this20.multiplier;
  1734. });
  1735. var new_pos = this.y_axis_values.map(function (value) {
  1736. return _this20.zero_line - value * _this20.multiplier;
  1737. });
  1738. var old_vals = this.y_old_axis_values;
  1739. var new_vals = this.y_axis_values;
  1740. var last_line_pos = old_pos[old_pos.length - 1];
  1741. this.y_axis_group.textContent = '';
  1742. this.make_new_axis_anim_lines(old_pos, new_pos, old_vals, new_vals, last_line_pos, this.add_and_animate_y_line.bind(this), this.y_axis_group);
  1743. }
  1744. }, {
  1745. key: 'make_anim_y_specifics',
  1746. value: function make_anim_y_specifics() {
  1747. var _this21 = this;
  1748. this.specific_y_group.textContent = '';
  1749. this.specific_values.map(function (d) {
  1750. _this21.add_and_animate_y_line(d.title, _this21.old_zero_line - d.value * _this21.old_multiplier, _this21.zero_line - d.value * _this21.multiplier, 0, _this21.specific_y_group, d.line_type, true);
  1751. });
  1752. }
  1753. }, {
  1754. key: 'make_new_axis_anim_lines',
  1755. value: function make_new_axis_anim_lines(old_pos, new_pos, old_vals, new_vals, last_line_pos, add_and_animate_line, group) {
  1756. var superimposed_positions = void 0,
  1757. superimposed_values = void 0;
  1758. var no_of_extras = new_vals.length - old_vals.length;
  1759. if (no_of_extras > 0) {
  1760. // More axis are needed
  1761. // First make only the superimposed (same position) ones
  1762. // Add in the extras at the end later
  1763. superimposed_positions = new_pos.slice(0, old_pos.length);
  1764. superimposed_values = new_vals.slice(0, old_vals.length);
  1765. } else {
  1766. // Axis have to be reduced
  1767. // Fake it by moving all current extra axis to the last position
  1768. // You'll need filler positions and values in the new arrays
  1769. var filler_vals = new Array(Math.abs(no_of_extras)).fill("");
  1770. superimposed_values = new_vals.concat(filler_vals);
  1771. var filler_pos = new Array(Math.abs(no_of_extras)).fill(last_line_pos + "F");
  1772. superimposed_positions = new_pos.concat(filler_pos);
  1773. }
  1774. superimposed_values.map(function (value, i) {
  1775. add_and_animate_line(value, old_pos[i], superimposed_positions[i], i, group);
  1776. });
  1777. if (no_of_extras > 0) {
  1778. // Add in extra axis in the end
  1779. // and then animate to new positions
  1780. var extra_values = new_vals.slice(old_vals.length);
  1781. var extra_positions = new_pos.slice(old_pos.length);
  1782. extra_values.map(function (value, i) {
  1783. add_and_animate_line(value, last_line_pos, extra_positions[i], i, group);
  1784. });
  1785. }
  1786. }
  1787. }, {
  1788. key: 'add_and_animate_y_line',
  1789. value: function add_and_animate_y_line(value, old_pos, new_pos, i, group, type) {
  1790. var specific = arguments.length > 6 && arguments[6] !== undefined ? arguments[6] : false;
  1791. var filler = false;
  1792. if (typeof new_pos === 'string') {
  1793. new_pos = parseInt(new_pos.substring(0, new_pos.length - 1));
  1794. filler = true;
  1795. }
  1796. var new_props = { transform: '0, ' + new_pos };
  1797. var old_props = { transform: '0, ' + old_pos };
  1798. if (filler) {
  1799. new_props['stroke-opacity'] = 0;
  1800. // old_props['stroke-opacity'] = 1;
  1801. }
  1802. var _get_y_axis_line_prop3 = this.get_y_axis_line_props(specific),
  1803. _get_y_axis_line_prop4 = slicedToArray(_get_y_axis_line_prop3, 4),
  1804. width = _get_y_axis_line_prop4[0],
  1805. text_end_at = _get_y_axis_line_prop4[1],
  1806. axis_line_class = _get_y_axis_line_prop4[2],
  1807. start_at = _get_y_axis_line_prop4[3];
  1808. var axis_label_class = !specific ? 'y-value-text' : 'specific-value';
  1809. value = !specific ? value : (value + "").toUpperCase();
  1810. var y_line = make_y_line(start_at, width, text_end_at, value, axis_label_class, axis_line_class, old_pos, // old position
  1811. value === 0 && i !== 0, // Non-first Zero line
  1812. type);
  1813. group.appendChild(y_line);
  1814. this.elements_to_animate && this.elements_to_animate.push([{ unit: y_line, array: [0], index: 0 }, new_props, 350, "easein", "translate", old_props]);
  1815. }
  1816. }, {
  1817. key: 'set_avg_unit_width_and_x_offset',
  1818. value: function set_avg_unit_width_and_x_offset() {
  1819. // Set the ... you get it
  1820. this.avg_unit_width = this.width / (this.x.length - 1);
  1821. this.x_offset = 0;
  1822. }
  1823. }, {
  1824. key: 'get_all_y_values',
  1825. value: function get_all_y_values() {
  1826. var all_values = [];
  1827. // Add in all the y values in the datasets
  1828. this.y.map(function (d) {
  1829. all_values = all_values.concat(d.values);
  1830. });
  1831. // Add in all the specific values
  1832. return all_values.concat(this.specific_values.map(function (d) {
  1833. return d.value;
  1834. }));
  1835. }
  1836. }, {
  1837. key: 'calc_y_dependencies',
  1838. value: function calc_y_dependencies() {
  1839. var _this22 = this;
  1840. this.y_min_tops = new Array(this.x_axis_positions.length).fill(9999);
  1841. this.y.map(function (d) {
  1842. d.y_tops = d.values.map(function (val) {
  1843. return float_2(_this22.zero_line - val * _this22.multiplier);
  1844. });
  1845. d.y_tops.map(function (y_top, i) {
  1846. if (y_top < _this22.y_min_tops[i]) {
  1847. _this22.y_min_tops[i] = y_top;
  1848. }
  1849. });
  1850. });
  1851. // this.chart_wrapper.removeChild(this.tip.container);
  1852. // this.make_tooltip();
  1853. }
  1854. }]);
  1855. return AxisChart;
  1856. }(BaseChart);
  1857. var BarChart = function (_AxisChart) {
  1858. inherits(BarChart, _AxisChart);
  1859. function BarChart(args) {
  1860. classCallCheck(this, BarChart);
  1861. var _this = possibleConstructorReturn(this, (BarChart.__proto__ || Object.getPrototypeOf(BarChart)).call(this, args));
  1862. _this.type = 'bar';
  1863. _this.x_axis_mode = args.x_axis_mode || 'tick';
  1864. _this.y_axis_mode = args.y_axis_mode || 'span';
  1865. _this.setup();
  1866. return _this;
  1867. }
  1868. createClass(BarChart, [{
  1869. key: 'setup_values',
  1870. value: function setup_values() {
  1871. get(BarChart.prototype.__proto__ || Object.getPrototypeOf(BarChart.prototype), 'setup_values', this).call(this);
  1872. this.x_offset = this.avg_unit_width;
  1873. this.unit_args = {
  1874. type: 'bar',
  1875. args: {
  1876. space_width: this.avg_unit_width / 2
  1877. }
  1878. };
  1879. }
  1880. }, {
  1881. key: 'make_overlay',
  1882. value: function make_overlay() {
  1883. // Just make one out of the first element
  1884. var index = this.x.length - 1;
  1885. var unit = this.y[0].svg_units[index];
  1886. this.update_current_data_point(index);
  1887. if (this.overlay) {
  1888. this.overlay.parentNode.removeChild(this.overlay);
  1889. }
  1890. this.overlay = unit.cloneNode();
  1891. this.overlay.style.fill = '#000000';
  1892. this.overlay.style.opacity = '0.4';
  1893. this.draw_area.appendChild(this.overlay);
  1894. }
  1895. }, {
  1896. key: 'bind_overlay',
  1897. value: function bind_overlay() {
  1898. var _this2 = this;
  1899. // on event, update overlay
  1900. this.parent.addEventListener('data-select', function (e) {
  1901. _this2.update_overlay(e.svg_unit);
  1902. });
  1903. }
  1904. }, {
  1905. key: 'bind_units',
  1906. value: function bind_units(units_array) {
  1907. var _this3 = this;
  1908. units_array.map(function (unit) {
  1909. unit.addEventListener('click', function () {
  1910. var index = unit.getAttribute('data-point-index');
  1911. _this3.update_current_data_point(index);
  1912. });
  1913. });
  1914. }
  1915. }, {
  1916. key: 'update_overlay',
  1917. value: function update_overlay(unit) {
  1918. var _this4 = this;
  1919. var attributes = [];
  1920. Object.keys(unit.attributes).map(function (index) {
  1921. attributes.push(unit.attributes[index]);
  1922. });
  1923. attributes.filter(function (attr) {
  1924. return attr.specified;
  1925. }).map(function (attr) {
  1926. _this4.overlay.setAttribute(attr.name, attr.nodeValue);
  1927. });
  1928. }
  1929. }, {
  1930. key: 'on_left_arrow',
  1931. value: function on_left_arrow() {
  1932. this.update_current_data_point(this.current_index - 1);
  1933. }
  1934. }, {
  1935. key: 'on_right_arrow',
  1936. value: function on_right_arrow() {
  1937. this.update_current_data_point(this.current_index + 1);
  1938. }
  1939. }, {
  1940. key: 'set_avg_unit_width_and_x_offset',
  1941. value: function set_avg_unit_width_and_x_offset() {
  1942. this.avg_unit_width = this.width / (this.x.length + 1);
  1943. this.x_offset = this.avg_unit_width;
  1944. }
  1945. }]);
  1946. return BarChart;
  1947. }(AxisChart);
  1948. var LineChart = function (_AxisChart) {
  1949. inherits(LineChart, _AxisChart);
  1950. function LineChart(args) {
  1951. classCallCheck(this, LineChart);
  1952. var _this = possibleConstructorReturn(this, (LineChart.__proto__ || Object.getPrototypeOf(LineChart)).call(this, args));
  1953. _this.x_axis_mode = args.x_axis_mode || 'span';
  1954. _this.y_axis_mode = args.y_axis_mode || 'span';
  1955. if (args.hasOwnProperty('show_dots')) {
  1956. _this.show_dots = args.show_dots;
  1957. } else {
  1958. _this.show_dots = 1;
  1959. }
  1960. _this.region_fill = args.region_fill;
  1961. if (Object.getPrototypeOf(_this) !== LineChart.prototype) {
  1962. return possibleConstructorReturn(_this);
  1963. }
  1964. _this.dot_radius = args.dot_radius || 4;
  1965. _this.heatline = args.heatline;
  1966. _this.type = 'line';
  1967. _this.setup();
  1968. return _this;
  1969. }
  1970. createClass(LineChart, [{
  1971. key: 'setup_graph_components',
  1972. value: function setup_graph_components() {
  1973. this.setup_path_groups();
  1974. get(LineChart.prototype.__proto__ || Object.getPrototypeOf(LineChart.prototype), 'setup_graph_components', this).call(this);
  1975. }
  1976. }, {
  1977. key: 'setup_path_groups',
  1978. value: function setup_path_groups() {
  1979. var _this2 = this;
  1980. this.paths_groups = [];
  1981. this.y.map(function (d, i) {
  1982. _this2.paths_groups[i] = $.createSVG('g', {
  1983. className: 'path-group path-group-' + i,
  1984. inside: _this2.draw_area
  1985. });
  1986. });
  1987. }
  1988. }, {
  1989. key: 'setup_values',
  1990. value: function setup_values() {
  1991. get(LineChart.prototype.__proto__ || Object.getPrototypeOf(LineChart.prototype), 'setup_values', this).call(this);
  1992. this.unit_args = {
  1993. type: 'dot',
  1994. args: { radius: this.dot_radius }
  1995. };
  1996. }
  1997. }, {
  1998. key: 'make_new_units_for_dataset',
  1999. value: function make_new_units_for_dataset(x_values, y_values, color, dataset_index, no_of_datasets, units_group, units_array, unit) {
  2000. if (this.show_dots) {
  2001. get(LineChart.prototype.__proto__ || Object.getPrototypeOf(LineChart.prototype), 'make_new_units_for_dataset', this).call(this, x_values, y_values, color, dataset_index, no_of_datasets, units_group, units_array, unit);
  2002. }
  2003. }
  2004. }, {
  2005. key: 'make_paths',
  2006. value: function make_paths() {
  2007. var _this3 = this;
  2008. this.y.map(function (d, i) {
  2009. _this3.make_path(d, i, _this3.x_axis_positions, d.y_tops, d.color || _this3.colors[i]);
  2010. });
  2011. }
  2012. }, {
  2013. key: 'make_path',
  2014. value: function make_path(d, i, x_positions, y_positions, color) {
  2015. var points_list = y_positions.map(function (y, i) {
  2016. return x_positions[i] + ',' + y;
  2017. });
  2018. var points_str = points_list.join("L");
  2019. this.paths_groups[i].textContent = '';
  2020. d.path = $.createSVG('path', {
  2021. inside: this.paths_groups[i],
  2022. className: 'stroke ' + color,
  2023. d: "M" + points_str
  2024. });
  2025. if (this.heatline) {
  2026. var gradient_id = this.make_gradient(color);
  2027. d.path.style.stroke = 'url(#' + gradient_id + ')';
  2028. }
  2029. if (this.region_fill) {
  2030. this.fill_region_for_dataset(d, i, color, points_str);
  2031. }
  2032. }
  2033. }, {
  2034. key: 'fill_region_for_dataset',
  2035. value: function fill_region_for_dataset(d, i, color, points_str) {
  2036. var gradient_id = this.make_gradient(color, true);
  2037. d.region_path = $.createSVG('path', {
  2038. inside: this.paths_groups[i],
  2039. className: 'region-fill',
  2040. d: "M" + ('0,' + this.zero_line + 'L') + points_str + ('L' + this.width + ',' + this.zero_line)
  2041. });
  2042. d.region_path.style.stroke = "none";
  2043. d.region_path.style.fill = 'url(#' + gradient_id + ')';
  2044. }
  2045. }, {
  2046. key: 'make_gradient',
  2047. value: function make_gradient(color) {
  2048. var lighter = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
  2049. var gradient_id = 'path-fill-gradient' + '-' + color;
  2050. var gradient_def = $.createSVG('linearGradient', {
  2051. inside: this.svg_defs,
  2052. id: gradient_id,
  2053. x1: 0,
  2054. x2: 0,
  2055. y1: 0,
  2056. y2: 1
  2057. });
  2058. var set_gradient_stop = function set_gradient_stop(grad_elem, offset, color, opacity) {
  2059. $.createSVG('stop', {
  2060. 'className': 'stop-color ' + color,
  2061. 'inside': grad_elem,
  2062. 'offset': offset,
  2063. 'stop-opacity': opacity
  2064. });
  2065. };
  2066. var opacities = [1, 0.6, 0.2];
  2067. if (lighter) {
  2068. opacities = [0.4, 0.2, 0];
  2069. }
  2070. set_gradient_stop(gradient_def, "0%", color, opacities[0]);
  2071. set_gradient_stop(gradient_def, "50%", color, opacities[1]);
  2072. set_gradient_stop(gradient_def, "100%", color, opacities[2]);
  2073. return gradient_id;
  2074. }
  2075. }]);
  2076. return LineChart;
  2077. }(AxisChart);
  2078. var ScatterChart = function (_LineChart) {
  2079. inherits(ScatterChart, _LineChart);
  2080. function ScatterChart(args) {
  2081. classCallCheck(this, ScatterChart);
  2082. var _this = possibleConstructorReturn(this, (ScatterChart.__proto__ || Object.getPrototypeOf(ScatterChart)).call(this, args));
  2083. _this.type = 'scatter';
  2084. if (!args.dot_radius) {
  2085. _this.dot_radius = 8;
  2086. } else {
  2087. _this.dot_radius = args.dot_radius;
  2088. }
  2089. _this.setup();
  2090. return _this;
  2091. }
  2092. createClass(ScatterChart, [{
  2093. key: 'setup_graph_components',
  2094. value: function setup_graph_components() {
  2095. this.setup_path_groups();
  2096. get(ScatterChart.prototype.__proto__ || Object.getPrototypeOf(ScatterChart.prototype), 'setup_graph_components', this).call(this);
  2097. }
  2098. }, {
  2099. key: 'setup_path_groups',
  2100. value: function setup_path_groups() {}
  2101. }, {
  2102. key: 'setup_values',
  2103. value: function setup_values() {
  2104. get(ScatterChart.prototype.__proto__ || Object.getPrototypeOf(ScatterChart.prototype), 'setup_values', this).call(this);
  2105. this.unit_args = {
  2106. type: 'dot',
  2107. args: { radius: this.dot_radius }
  2108. };
  2109. }
  2110. }, {
  2111. key: 'make_paths',
  2112. value: function make_paths() {}
  2113. }, {
  2114. key: 'make_path',
  2115. value: function make_path() {}
  2116. }]);
  2117. return ScatterChart;
  2118. }(LineChart);
  2119. var PercentageChart = function (_BaseChart) {
  2120. inherits(PercentageChart, _BaseChart);
  2121. function PercentageChart(args) {
  2122. classCallCheck(this, PercentageChart);
  2123. var _this = possibleConstructorReturn(this, (PercentageChart.__proto__ || Object.getPrototypeOf(PercentageChart)).call(this, args));
  2124. _this.type = 'percentage';
  2125. _this.max_slices = 10;
  2126. _this.max_legend_points = 6;
  2127. _this.setup();
  2128. return _this;
  2129. }
  2130. createClass(PercentageChart, [{
  2131. key: 'make_chart_area',
  2132. value: function make_chart_area() {
  2133. this.chart_wrapper.className += ' ' + 'graph-focus-margin';
  2134. this.chart_wrapper.style.marginTop = '45px';
  2135. this.stats_wrapper.className += ' ' + 'graph-focus-margin';
  2136. this.stats_wrapper.style.marginBottom = '30px';
  2137. this.stats_wrapper.style.paddingTop = '0px';
  2138. }
  2139. }, {
  2140. key: 'make_draw_area',
  2141. value: function make_draw_area() {
  2142. this.chart_div = $.create('div', {
  2143. className: 'div',
  2144. inside: this.chart_wrapper
  2145. });
  2146. this.chart = $.create('div', {
  2147. className: 'progress-chart',
  2148. inside: this.chart_div
  2149. });
  2150. }
  2151. }, {
  2152. key: 'setup_components',
  2153. value: function setup_components() {
  2154. this.percentage_bar = $.create('div', {
  2155. className: 'progress',
  2156. inside: this.chart
  2157. });
  2158. }
  2159. }, {
  2160. key: 'setup_values',
  2161. value: function setup_values() {
  2162. var _this2 = this;
  2163. this.slice_totals = [];
  2164. var all_totals = this.data.labels.map(function (d, i) {
  2165. var total = 0;
  2166. _this2.data.datasets.map(function (e) {
  2167. total += e.values[i];
  2168. });
  2169. return [total, d];
  2170. }).filter(function (d) {
  2171. return d[0] > 0;
  2172. }); // keep only positive results
  2173. var totals = all_totals;
  2174. if (all_totals.length > this.max_slices) {
  2175. all_totals.sort(function (a, b) {
  2176. return b[0] - a[0];
  2177. });
  2178. totals = all_totals.slice(0, this.max_slices - 1);
  2179. var others = all_totals.slice(this.max_slices - 1);
  2180. var sum_of_others = 0;
  2181. others.map(function (d) {
  2182. sum_of_others += d[0];
  2183. });
  2184. totals.push([sum_of_others, 'Rest']);
  2185. this.colors[this.max_slices - 1] = 'grey';
  2186. }
  2187. this.labels = [];
  2188. totals.map(function (d) {
  2189. _this2.slice_totals.push(d[0]);
  2190. _this2.labels.push(d[1]);
  2191. });
  2192. this.legend_totals = this.slice_totals.slice(0, this.max_legend_points);
  2193. }
  2194. }, {
  2195. key: 'make_graph_components',
  2196. value: function make_graph_components() {
  2197. var _this3 = this;
  2198. this.grand_total = this.slice_totals.reduce(function (a, b) {
  2199. return a + b;
  2200. }, 0);
  2201. this.slices = [];
  2202. this.slice_totals.map(function (total, i) {
  2203. var slice = $.create('div', {
  2204. className: 'progress-bar background ' + _this3.colors[i],
  2205. inside: _this3.percentage_bar,
  2206. styles: {
  2207. width: total * 100 / _this3.grand_total + "%"
  2208. }
  2209. });
  2210. _this3.slices.push(slice);
  2211. });
  2212. }
  2213. }, {
  2214. key: 'bind_tooltip',
  2215. value: function bind_tooltip() {
  2216. var _this4 = this;
  2217. this.slices.map(function (slice, i) {
  2218. slice.addEventListener('mouseenter', function () {
  2219. var g_off = $.offset(_this4.chart_wrapper),
  2220. p_off = $.offset(slice);
  2221. var x = p_off.left - g_off.left + slice.offsetWidth / 2;
  2222. var y = p_off.top - g_off.top - 6;
  2223. var title = (_this4.formatted_labels && _this4.formatted_labels.length > 0 ? _this4.formatted_labels[i] : _this4.labels[i]) + ': ';
  2224. var percent = (_this4.slice_totals[i] * 100 / _this4.grand_total).toFixed(1);
  2225. _this4.tip.set_values(x, y, title, percent + "%");
  2226. _this4.tip.show_tip();
  2227. });
  2228. });
  2229. }
  2230. }, {
  2231. key: 'show_summary',
  2232. value: function show_summary() {
  2233. var _this5 = this;
  2234. var x_values = this.formatted_labels && this.formatted_labels.length > 0 ? this.formatted_labels : this.labels;
  2235. this.legend_totals.map(function (d, i) {
  2236. if (d) {
  2237. var stats = $.create('div', {
  2238. className: 'stats',
  2239. inside: _this5.stats_wrapper
  2240. });
  2241. stats.innerHTML = '<span class="indicator ' + _this5.colors[i] + '">\n\t\t\t\t\t<span class="text-muted">' + x_values[i] + ':</span>\n\t\t\t\t\t' + d + '\n\t\t\t\t</span>';
  2242. }
  2243. });
  2244. }
  2245. }]);
  2246. return PercentageChart;
  2247. }(BaseChart);
  2248. function limit_color(r) {
  2249. if (r > 255) return 255;else if (r < 0) return 0;
  2250. return r;
  2251. }
  2252. function lighten_darken_color(col, amt) {
  2253. var usePound = false;
  2254. if (col[0] == "#") {
  2255. col = col.slice(1);
  2256. usePound = true;
  2257. }
  2258. var num = parseInt(col, 16);
  2259. var r = limit_color((num >> 16) + amt);
  2260. var b = limit_color((num >> 8 & 0x00FF) + amt);
  2261. var g = limit_color((num & 0x0000FF) + amt);
  2262. return (usePound ? "#" : "") + (g | b << 8 | r << 16).toString(16);
  2263. }
  2264. function is_valid_color(string) {
  2265. // https://stackoverflow.com/a/8027444/6495043
  2266. return (/(^#[0-9A-F]{6}$)|(^#[0-9A-F]{3}$)/i.test(string)
  2267. );
  2268. }
  2269. var ANGLE_RATIO = Math.PI / 180;
  2270. var FULL_ANGLE = 360;
  2271. var PieChart = function (_BaseChart) {
  2272. inherits(PieChart, _BaseChart);
  2273. function PieChart(args) {
  2274. classCallCheck(this, PieChart);
  2275. var _this = possibleConstructorReturn(this, (PieChart.__proto__ || Object.getPrototypeOf(PieChart)).call(this, args));
  2276. _this.type = 'pie';
  2277. _this.elements_to_animate = null;
  2278. _this.hoverRadio = args.hoverRadio || 0.1;
  2279. _this.max_slices = 10;
  2280. _this.max_legend_points = 6;
  2281. _this.isAnimate = false;
  2282. _this.colors = args.colors;
  2283. _this.startAngle = args.startAngle || 0;
  2284. _this.clockWise = args.clockWise || false;
  2285. if (!_this.colors || _this.colors.length < _this.data.labels.length) {
  2286. _this.colors = ['#7cd6fd', '#5e64ff', '#743ee2', '#ff5858', '#ffa00a', '#FEEF72', '#28a745', '#98d85b', '#b554ff', '#ffa3ef'];
  2287. }
  2288. _this.mouseMove = _this.mouseMove.bind(_this);
  2289. _this.mouseLeave = _this.mouseLeave.bind(_this);
  2290. _this.setup();
  2291. return _this;
  2292. }
  2293. createClass(PieChart, [{
  2294. key: 'setup_values',
  2295. value: function setup_values() {
  2296. var _this2 = this;
  2297. this.centerX = this.width / 2;
  2298. this.centerY = this.height / 2;
  2299. this.radius = this.height > this.width ? this.centerX : this.centerY;
  2300. this.slice_totals = [];
  2301. var all_totals = this.data.labels.map(function (d, i) {
  2302. var total = 0;
  2303. _this2.data.datasets.map(function (e) {
  2304. total += e.values[i];
  2305. });
  2306. return [total, d];
  2307. }).filter(function (d) {
  2308. return d[0] > 0;
  2309. }); // keep only positive results
  2310. var totals = all_totals;
  2311. if (all_totals.length > this.max_slices) {
  2312. all_totals.sort(function (a, b) {
  2313. return b[0] - a[0];
  2314. });
  2315. totals = all_totals.slice(0, this.max_slices - 1);
  2316. var others = all_totals.slice(this.max_slices - 1);
  2317. var sum_of_others = 0;
  2318. others.map(function (d) {
  2319. sum_of_others += d[0];
  2320. });
  2321. totals.push([sum_of_others, 'Rest']);
  2322. this.colors[this.max_slices - 1] = 'grey';
  2323. }
  2324. this.labels = [];
  2325. totals.map(function (d) {
  2326. _this2.slice_totals.push(d[0]);
  2327. _this2.labels.push(d[1]);
  2328. });
  2329. this.legend_totals = this.slice_totals.slice(0, this.max_legend_points);
  2330. }
  2331. }, {
  2332. key: 'makeArcPath',
  2333. value: function makeArcPath(startPosition, endPosition) {
  2334. var centerX = this.centerX,
  2335. centerY = this.centerY,
  2336. radius = this.radius,
  2337. clockWise = this.clockWise;
  2338. return 'M' + centerX + ' ' + centerY + ' L' + (centerX + startPosition.x) + ' ' + (centerY + startPosition.y) + ' A ' + radius + ' ' + radius + ' 0 0 ' + (clockWise ? 1 : 0) + ' ' + (centerX + endPosition.x) + ' ' + (centerY + endPosition.y) + ' z';
  2339. }
  2340. }, {
  2341. key: 'make_graph_components',
  2342. value: function make_graph_components(init) {
  2343. var _this3 = this;
  2344. var radius = this.radius,
  2345. clockWise = this.clockWise;
  2346. this.grand_total = this.slice_totals.reduce(function (a, b) {
  2347. return a + b;
  2348. }, 0);
  2349. var prevSlicesProperties = this.slicesProperties || [];
  2350. this.slices = [];
  2351. this.elements_to_animate = [];
  2352. this.slicesProperties = [];
  2353. var curAngle = 180 - this.startAngle;
  2354. this.slice_totals.map(function (total, i) {
  2355. var startAngle = curAngle;
  2356. var originDiffAngle = total / _this3.grand_total * FULL_ANGLE;
  2357. var diffAngle = clockWise ? -originDiffAngle : originDiffAngle;
  2358. var endAngle = curAngle = curAngle + diffAngle;
  2359. var startPosition = PieChart.getPositionByAngle(startAngle, radius);
  2360. var endPosition = PieChart.getPositionByAngle(endAngle, radius);
  2361. var prevProperty = init && prevSlicesProperties[i];
  2362. var curStart = void 0,
  2363. curEnd = void 0;
  2364. if (init) {
  2365. curStart = prevProperty ? prevProperty.startPosition : startPosition;
  2366. curEnd = prevProperty ? prevProperty.endPosition : startPosition;
  2367. } else {
  2368. curStart = startPosition;
  2369. curEnd = endPosition;
  2370. }
  2371. var curPath = _this3.makeArcPath(curStart, curEnd);
  2372. var slice = $.createSVG('path', {
  2373. inside: _this3.draw_area,
  2374. className: 'pie-path',
  2375. style: 'transition:transform .3s;',
  2376. d: curPath,
  2377. fill: _this3.colors[i]
  2378. });
  2379. _this3.slices.push(slice);
  2380. _this3.slicesProperties.push({
  2381. startPosition: startPosition,
  2382. endPosition: endPosition,
  2383. value: total,
  2384. total: _this3.grand_total,
  2385. startAngle: startAngle,
  2386. endAngle: endAngle,
  2387. angle: diffAngle
  2388. });
  2389. if (init) {
  2390. _this3.elements_to_animate.push([{ unit: slice, array: _this3.slices, index: _this3.slices.length - 1 }, { d: _this3.makeArcPath(startPosition, endPosition) }, 650, "easein", null, {
  2391. d: curPath
  2392. }]);
  2393. }
  2394. });
  2395. if (init) {
  2396. this.run_animation();
  2397. }
  2398. }
  2399. }, {
  2400. key: 'run_animation',
  2401. value: function run_animation() {
  2402. var _this4 = this;
  2403. // if(this.isAnimate) return ;
  2404. // this.isAnimate = true;
  2405. if (!this.elements_to_animate || this.elements_to_animate.length === 0) return;
  2406. var anim_svg = runSVGAnimation(this.svg, this.elements_to_animate);
  2407. if (this.svg.parentNode == this.chart_wrapper) {
  2408. this.chart_wrapper.removeChild(this.svg);
  2409. this.chart_wrapper.appendChild(anim_svg);
  2410. }
  2411. // Replace the new svg (data has long been replaced)
  2412. setTimeout(function () {
  2413. // this.isAnimate = false;
  2414. if (anim_svg.parentNode == _this4.chart_wrapper) {
  2415. _this4.chart_wrapper.removeChild(anim_svg);
  2416. _this4.chart_wrapper.appendChild(_this4.svg);
  2417. }
  2418. }, 650);
  2419. }
  2420. }, {
  2421. key: 'calTranslateByAngle',
  2422. value: function calTranslateByAngle(property) {
  2423. var radius = this.radius,
  2424. hoverRadio = this.hoverRadio;
  2425. var position = PieChart.getPositionByAngle(property.startAngle + property.angle / 2, radius);
  2426. return 'translate3d(' + position.x * hoverRadio + 'px,' + position.y * hoverRadio + 'px,0)';
  2427. }
  2428. }, {
  2429. key: 'hoverSlice',
  2430. value: function hoverSlice(path, i, flag, e) {
  2431. if (!path) return;
  2432. if (flag) {
  2433. transform(path, this.calTranslateByAngle(this.slicesProperties[i]));
  2434. path.setAttribute('fill', lighten_darken_color(this.colors[i], 50));
  2435. var g_off = $.offset(this.svg);
  2436. var x = e.pageX - g_off.left + 10;
  2437. var y = e.pageY - g_off.top - 10;
  2438. var title = (this.formatted_labels && this.formatted_labels.length > 0 ? this.formatted_labels[i] : this.labels[i]) + ': ';
  2439. var percent = (this.slice_totals[i] * 100 / this.grand_total).toFixed(1);
  2440. this.tip.set_values(x, y, title, percent + "%");
  2441. this.tip.show_tip();
  2442. } else {
  2443. transform(path, 'translate3d(0,0,0)');
  2444. this.tip.hide_tip();
  2445. path.setAttribute('fill', this.colors[i]);
  2446. }
  2447. }
  2448. }, {
  2449. key: 'mouseMove',
  2450. value: function mouseMove(e) {
  2451. var target = e.target;
  2452. var prevIndex = this.curActiveSliceIndex;
  2453. var prevAcitve = this.curActiveSlice;
  2454. for (var i = 0; i < this.slices.length; i++) {
  2455. if (target === this.slices[i]) {
  2456. this.hoverSlice(prevAcitve, prevIndex, false);
  2457. this.curActiveSlice = target;
  2458. this.curActiveSliceIndex = i;
  2459. this.hoverSlice(target, i, true, e);
  2460. break;
  2461. }
  2462. }
  2463. }
  2464. }, {
  2465. key: 'mouseLeave',
  2466. value: function mouseLeave() {
  2467. this.hoverSlice(this.curActiveSlice, this.curActiveSliceIndex, false);
  2468. }
  2469. }, {
  2470. key: 'bind_tooltip',
  2471. value: function bind_tooltip() {
  2472. this.draw_area.addEventListener('mousemove', this.mouseMove);
  2473. this.draw_area.addEventListener('mouseleave', this.mouseLeave);
  2474. }
  2475. }, {
  2476. key: 'show_summary',
  2477. value: function show_summary() {
  2478. var _this5 = this;
  2479. var x_values = this.formatted_labels && this.formatted_labels.length > 0 ? this.formatted_labels : this.labels;
  2480. this.legend_totals.map(function (d, i) {
  2481. if (d) {
  2482. var stats = $.create('div', {
  2483. className: 'stats',
  2484. inside: _this5.stats_wrapper
  2485. });
  2486. stats.innerHTML = '<span class="indicator">\n\t\t\t\t\t<i style="background-color:' + _this5.colors[i] + ';"></i>\n\t\t\t\t\t<span class="text-muted">' + x_values[i] + ':</span>\n\t\t\t\t\t' + d + '\n\t\t\t\t</span>';
  2487. }
  2488. });
  2489. }
  2490. }], [{
  2491. key: 'getPositionByAngle',
  2492. value: function getPositionByAngle(angle, radius) {
  2493. return {
  2494. x: Math.sin(angle * ANGLE_RATIO) * radius,
  2495. y: Math.cos(angle * ANGLE_RATIO) * radius
  2496. };
  2497. }
  2498. }]);
  2499. return PieChart;
  2500. }(BaseChart);
  2501. // Playing around with dates
  2502. // https://stackoverflow.com/a/11252167/6495043
  2503. function treat_as_utc(date_str) {
  2504. var result = new Date(date_str);
  2505. result.setMinutes(result.getMinutes() - result.getTimezoneOffset());
  2506. return result;
  2507. }
  2508. function get_dd_mm_yyyy(date) {
  2509. var dd = date.getDate();
  2510. var mm = date.getMonth() + 1; // getMonth() is zero-based
  2511. return [(dd > 9 ? '' : '0') + dd, (mm > 9 ? '' : '0') + mm, date.getFullYear()].join('-');
  2512. }
  2513. function get_weeks_between(start_date_str, end_date_str) {
  2514. return Math.ceil(get_days_between(start_date_str, end_date_str) / 7);
  2515. }
  2516. function get_days_between(start_date_str, end_date_str) {
  2517. var milliseconds_per_day = 24 * 60 * 60 * 1000;
  2518. return (treat_as_utc(end_date_str) - treat_as_utc(start_date_str)) / milliseconds_per_day;
  2519. }
  2520. // mutates
  2521. function add_days(date, number_of_days) {
  2522. date.setDate(date.getDate() + number_of_days);
  2523. }
  2524. // export function get_month_name() {}
  2525. var Heatmap = function (_BaseChart) {
  2526. inherits(Heatmap, _BaseChart);
  2527. function Heatmap(_ref) {
  2528. var _ref$start = _ref.start,
  2529. start = _ref$start === undefined ? '' : _ref$start,
  2530. _ref$domain = _ref.domain,
  2531. domain = _ref$domain === undefined ? '' : _ref$domain,
  2532. _ref$subdomain = _ref.subdomain,
  2533. subdomain = _ref$subdomain === undefined ? '' : _ref$subdomain,
  2534. _ref$data = _ref.data,
  2535. data = _ref$data === undefined ? {} : _ref$data,
  2536. _ref$discrete_domains = _ref.discrete_domains,
  2537. discrete_domains = _ref$discrete_domains === undefined ? 0 : _ref$discrete_domains,
  2538. _ref$count_label = _ref.count_label,
  2539. count_label = _ref$count_label === undefined ? '' : _ref$count_label,
  2540. _ref$legend_colors = _ref.legend_colors,
  2541. legend_colors = _ref$legend_colors === undefined ? [] : _ref$legend_colors;
  2542. classCallCheck(this, Heatmap);
  2543. var _this = possibleConstructorReturn(this, (Heatmap.__proto__ || Object.getPrototypeOf(Heatmap)).call(this, arguments[0]));
  2544. _this.type = 'heatmap';
  2545. _this.domain = domain;
  2546. _this.subdomain = subdomain;
  2547. _this.data = data;
  2548. _this.discrete_domains = discrete_domains;
  2549. _this.count_label = count_label;
  2550. var today = new Date();
  2551. _this.start = start || add_days(today, 365);
  2552. legend_colors = legend_colors.slice(0, 5);
  2553. _this.legend_colors = _this.validate_colors(legend_colors) ? legend_colors : ['#ebedf0', '#c6e48b', '#7bc96f', '#239a3b', '#196127'];
  2554. // Hardcoded for a fixed 5-color theme,
  2555. // More colors are difficult to parse visually
  2556. _this.distribution_size = 5;
  2557. _this.translate_x = 0;
  2558. _this.setup();
  2559. return _this;
  2560. }
  2561. createClass(Heatmap, [{
  2562. key: 'validate_colors',
  2563. value: function validate_colors(colors) {
  2564. if (colors.length < 5) return 0;
  2565. var valid = 1;
  2566. colors.forEach(function (string) {
  2567. if (!is_valid_color(string)) {
  2568. valid = 0;
  2569. console.warn('"' + string + '" is not a valid color.');
  2570. }
  2571. }, this);
  2572. return valid;
  2573. }
  2574. }, {
  2575. key: 'setup_base_values',
  2576. value: function setup_base_values() {
  2577. this.today = new Date();
  2578. if (!this.start) {
  2579. this.start = new Date();
  2580. this.start.setFullYear(this.start.getFullYear() - 1);
  2581. }
  2582. this.first_week_start = new Date(this.start.toDateString());
  2583. this.last_week_start = new Date(this.today.toDateString());
  2584. if (this.first_week_start.getDay() !== 7) {
  2585. add_days(this.first_week_start, -1 * this.first_week_start.getDay());
  2586. }
  2587. if (this.last_week_start.getDay() !== 7) {
  2588. add_days(this.last_week_start, -1 * this.last_week_start.getDay());
  2589. }
  2590. this.no_of_cols = get_weeks_between(this.first_week_start + '', this.last_week_start + '') + 1;
  2591. }
  2592. }, {
  2593. key: 'set_width',
  2594. value: function set_width() {
  2595. this.base_width = (this.no_of_cols + 3) * 12;
  2596. if (this.discrete_domains) {
  2597. this.base_width += 12 * 12;
  2598. }
  2599. }
  2600. }, {
  2601. key: 'setup_components',
  2602. value: function setup_components() {
  2603. this.domain_label_group = $.createSVG("g", {
  2604. className: "domain-label-group chart-label",
  2605. inside: this.draw_area
  2606. });
  2607. this.data_groups = $.createSVG("g", {
  2608. className: "data-groups",
  2609. inside: this.draw_area,
  2610. transform: 'translate(0, 20)'
  2611. });
  2612. }
  2613. }, {
  2614. key: 'setup_values',
  2615. value: function setup_values() {
  2616. var _this2 = this;
  2617. this.domain_label_group.textContent = '';
  2618. this.data_groups.textContent = '';
  2619. var data_values = Object.keys(this.data).map(function (key) {
  2620. return _this2.data[key];
  2621. });
  2622. this.distribution = calc_distribution(data_values, this.distribution_size);
  2623. this.month_names = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
  2624. this.render_all_weeks_and_store_x_values(this.no_of_cols);
  2625. }
  2626. }, {
  2627. key: 'render_all_weeks_and_store_x_values',
  2628. value: function render_all_weeks_and_store_x_values(no_of_weeks) {
  2629. var current_week_sunday = new Date(this.first_week_start);
  2630. this.week_col = 0;
  2631. this.current_month = current_week_sunday.getMonth();
  2632. this.months = [this.current_month + ''];
  2633. this.month_weeks = {}, this.month_start_points = [];
  2634. this.month_weeks[this.current_month] = 0;
  2635. this.month_start_points.push(13);
  2636. for (var i = 0; i < no_of_weeks; i++) {
  2637. var data_group = void 0,
  2638. month_change = 0;
  2639. var day = new Date(current_week_sunday);
  2640. var _get_week_squares_gro = this.get_week_squares_group(day, this.week_col);
  2641. var _get_week_squares_gro2 = slicedToArray(_get_week_squares_gro, 2);
  2642. data_group = _get_week_squares_gro2[0];
  2643. month_change = _get_week_squares_gro2[1];
  2644. this.data_groups.appendChild(data_group);
  2645. this.week_col += 1 + parseInt(this.discrete_domains && month_change);
  2646. this.month_weeks[this.current_month]++;
  2647. if (month_change) {
  2648. this.current_month = (this.current_month + 1) % 12;
  2649. this.months.push(this.current_month + '');
  2650. this.month_weeks[this.current_month] = 1;
  2651. }
  2652. add_days(current_week_sunday, 7);
  2653. }
  2654. this.render_month_labels();
  2655. }
  2656. }, {
  2657. key: 'get_week_squares_group',
  2658. value: function get_week_squares_group(current_date, index) {
  2659. var no_of_weekdays = 7;
  2660. var square_side = 10;
  2661. var cell_padding = 2;
  2662. var step = 1;
  2663. var today_time = this.today.getTime();
  2664. var month_change = 0;
  2665. var week_col_change = 0;
  2666. var data_group = $.createSVG("g", {
  2667. className: "data-group",
  2668. inside: this.data_groups
  2669. });
  2670. for (var y = 0, i = 0; i < no_of_weekdays; i += step, y += square_side + cell_padding) {
  2671. var data_value = 0;
  2672. var color_index = 0;
  2673. var current_timestamp = current_date.getTime() / 1000;
  2674. var timestamp = Math.floor(current_timestamp - current_timestamp % 86400).toFixed(1);
  2675. if (this.data[timestamp]) {
  2676. data_value = this.data[timestamp];
  2677. }
  2678. if (this.data[Math.round(timestamp)]) {
  2679. data_value = this.data[Math.round(timestamp)];
  2680. }
  2681. if (data_value) {
  2682. color_index = get_max_checkpoint(data_value, this.distribution);
  2683. }
  2684. var x = 13 + (index + week_col_change) * 12;
  2685. $.createSVG("rect", {
  2686. className: 'day',
  2687. inside: data_group,
  2688. x: x,
  2689. y: y,
  2690. width: square_side,
  2691. height: square_side,
  2692. fill: this.legend_colors[color_index],
  2693. 'data-date': get_dd_mm_yyyy(current_date),
  2694. 'data-value': data_value,
  2695. 'data-day': current_date.getDay()
  2696. });
  2697. var next_date = new Date(current_date);
  2698. add_days(next_date, 1);
  2699. if (next_date.getTime() > today_time) break;
  2700. if (next_date.getMonth() - current_date.getMonth()) {
  2701. month_change = 1;
  2702. if (this.discrete_domains) {
  2703. week_col_change = 1;
  2704. }
  2705. this.month_start_points.push(13 + (index + week_col_change) * 12);
  2706. }
  2707. current_date = next_date;
  2708. }
  2709. return [data_group, month_change];
  2710. }
  2711. }, {
  2712. key: 'render_month_labels',
  2713. value: function render_month_labels() {
  2714. var _this3 = this;
  2715. // this.first_month_label = 1;
  2716. // if (this.first_week_start.getDate() > 8) {
  2717. // this.first_month_label = 0;
  2718. // }
  2719. // this.last_month_label = 1;
  2720. // let first_month = this.months.shift();
  2721. // let first_month_start = this.month_start_points.shift();
  2722. // render first month if
  2723. // let last_month = this.months.pop();
  2724. // let last_month_start = this.month_start_points.pop();
  2725. // render last month if
  2726. this.months.shift();
  2727. this.month_start_points.shift();
  2728. this.months.pop();
  2729. this.month_start_points.pop();
  2730. this.month_start_points.map(function (start, i) {
  2731. var month_name = _this3.month_names[_this3.months[i]].substring(0, 3);
  2732. $.createSVG('text', {
  2733. className: 'y-value-text',
  2734. inside: _this3.domain_label_group,
  2735. x: start + 12,
  2736. y: 10,
  2737. dy: '.32em',
  2738. innerHTML: month_name
  2739. });
  2740. });
  2741. }
  2742. }, {
  2743. key: 'make_graph_components',
  2744. value: function make_graph_components() {
  2745. Array.prototype.slice.call(this.container.querySelectorAll('.graph-stats-container, .sub-title, .title')).map(function (d) {
  2746. d.style.display = 'None';
  2747. });
  2748. this.chart_wrapper.style.marginTop = '0px';
  2749. this.chart_wrapper.style.paddingTop = '0px';
  2750. }
  2751. }, {
  2752. key: 'bind_tooltip',
  2753. value: function bind_tooltip() {
  2754. var _this4 = this;
  2755. Array.prototype.slice.call(document.querySelectorAll(".data-group .day")).map(function (el) {
  2756. el.addEventListener('mouseenter', function (e) {
  2757. var count = e.target.getAttribute('data-value');
  2758. var date_parts = e.target.getAttribute('data-date').split('-');
  2759. var month = _this4.month_names[parseInt(date_parts[1]) - 1].substring(0, 3);
  2760. var g_off = _this4.chart_wrapper.getBoundingClientRect(),
  2761. p_off = e.target.getBoundingClientRect();
  2762. var width = parseInt(e.target.getAttribute('width'));
  2763. var x = p_off.left - g_off.left + (width + 2) / 2;
  2764. var y = p_off.top - g_off.top - (width + 2) / 2;
  2765. var value = count + ' ' + _this4.count_label;
  2766. var name = ' on ' + month + ' ' + date_parts[0] + ', ' + date_parts[2];
  2767. _this4.tip.set_values(x, y, name, value, [], 1);
  2768. _this4.tip.show_tip();
  2769. });
  2770. });
  2771. }
  2772. }, {
  2773. key: 'update',
  2774. value: function update(data) {
  2775. this.data = data;
  2776. this.setup_values();
  2777. this.bind_tooltip();
  2778. }
  2779. }]);
  2780. return Heatmap;
  2781. }(BaseChart);
  2782. var chartTypes = {
  2783. line: LineChart,
  2784. bar: BarChart,
  2785. scatter: ScatterChart,
  2786. percentage: PercentageChart,
  2787. heatmap: Heatmap,
  2788. pie: PieChart
  2789. };
  2790. function getChartByType() {
  2791. var chartType = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'line';
  2792. var options = arguments[1];
  2793. if (!chartTypes[chartType]) {
  2794. return new LineChart(options);
  2795. }
  2796. return new chartTypes[chartType](options);
  2797. }
  2798. var Chart = function Chart(args) {
  2799. classCallCheck(this, Chart);
  2800. return getChartByType(args.type, arguments[0]);
  2801. };
  2802. export default Chart;