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.
 
 
 

2773 lines
67 KiB

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