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.
 
 
 

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