Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.
 
 
 

3349 строки
91 KiB

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