您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符
 
 
 

2882 行
70 KiB

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