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

2892 line
70 KiB

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