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.
 
 
 

3648 line
86 KiB

  1. function $(expr, con) {
  2. return typeof expr === "string"? (con || document).querySelector(expr) : expr || null;
  3. }
  4. $.create = (tag, o) => {
  5. var element = document.createElement(tag);
  6. for (var i in o) {
  7. var val = o[i];
  8. if (i === "inside") {
  9. $(val).appendChild(element);
  10. }
  11. else if (i === "around") {
  12. var ref = $(val);
  13. ref.parentNode.insertBefore(element, ref);
  14. element.appendChild(ref);
  15. } else if (i === "styles") {
  16. if(typeof val === "object") {
  17. Object.keys(val).map(prop => {
  18. element.style[prop] = val[prop];
  19. });
  20. }
  21. } else if (i in element ) {
  22. element[i] = val;
  23. }
  24. else {
  25. element.setAttribute(i, val);
  26. }
  27. }
  28. return element;
  29. };
  30. function getOffset(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. function fire(target, type, properties) {
  57. var evt = document.createEvent("HTMLEvents");
  58. evt.initEvent(type, true, true );
  59. for (var j in properties) {
  60. evt[j] = properties[j];
  61. }
  62. return target.dispatchEvent(evt);
  63. }
  64. // https://css-tricks.com/snippets/javascript/loop-queryselectorall-matches/
  65. const BASE_MEASURES = {
  66. margins: {
  67. top: 10,
  68. bottom: 10,
  69. left: 20,
  70. right: 20
  71. },
  72. paddings: {
  73. top: 20,
  74. bottom: 40,
  75. left: 30,
  76. right: 10
  77. },
  78. baseHeight: 240,
  79. titleHeight: 20,
  80. legendHeight: 30,
  81. titleFontSize: 12,
  82. };
  83. function getExtraHeight(m) {
  84. let totalExtraHeight = m.margins.top + m.margins.bottom
  85. + m.paddings.top + m.paddings.bottom
  86. + m.titleHeight + m.legendHeight;
  87. return totalExtraHeight;
  88. }
  89. function getExtraWidth(m) {
  90. let totalExtraWidth = m.margins.left + m.margins.right
  91. + m.paddings.left + m.paddings.right;
  92. return totalExtraWidth;
  93. }
  94. const INIT_CHART_UPDATE_TIMEOUT = 700;
  95. const CHART_POST_ANIMATE_TIMEOUT = 400;
  96. const DEFAULT_AXIS_CHART_TYPE = 'line';
  97. const AXIS_DATASET_CHART_TYPES = ['line', 'bar'];
  98. const AXIS_LEGEND_BAR_SIZE = 100;
  99. const BAR_CHART_SPACE_RATIO = 0.5;
  100. const MIN_BAR_PERCENT_HEIGHT = 0.01;
  101. const LINE_CHART_DOT_SIZE = 4;
  102. const DOT_OVERLAY_SIZE_INCR = 4;
  103. const PERCENTAGE_BAR_DEFAULT_HEIGHT = 20;
  104. const PERCENTAGE_BAR_DEFAULT_DEPTH = 2;
  105. // Fixed 5-color theme,
  106. // More colors are difficult to parse visually
  107. const HEATMAP_DISTRIBUTION_SIZE = 5;
  108. const HEATMAP_SQUARE_SIZE = 10;
  109. const HEATMAP_GUTTER_SIZE = 2;
  110. const DEFAULT_CHAR_WIDTH = 7;
  111. const TOOLTIP_POINTER_TRIANGLE_HEIGHT = 5;
  112. const DEFAULT_CHART_COLORS = ['light-blue', 'blue', 'violet', 'red', 'orange',
  113. 'yellow', 'green', 'light-green', 'purple', 'magenta', 'light-grey', 'dark-grey'];
  114. const HEATMAP_COLORS_GREEN = ['#ebedf0', '#c6e48b', '#7bc96f', '#239a3b', '#196127'];
  115. const DEFAULT_COLORS = {
  116. bar: DEFAULT_CHART_COLORS,
  117. line: DEFAULT_CHART_COLORS,
  118. pie: DEFAULT_CHART_COLORS,
  119. percentage: DEFAULT_CHART_COLORS,
  120. heatmap: HEATMAP_COLORS_GREEN
  121. };
  122. // Universal constants
  123. const ANGLE_RATIO = Math.PI / 180;
  124. const FULL_ANGLE = 360;
  125. class SvgTip {
  126. constructor({
  127. parent = null,
  128. colors = []
  129. }) {
  130. this.parent = parent;
  131. this.colors = colors;
  132. this.titleName = '';
  133. this.titleValue = '';
  134. this.listValues = [];
  135. this.titleValueFirst = 0;
  136. this.x = 0;
  137. this.y = 0;
  138. this.top = 0;
  139. this.left = 0;
  140. this.setup();
  141. }
  142. setup() {
  143. this.makeTooltip();
  144. }
  145. refresh() {
  146. this.fill();
  147. this.calcPosition();
  148. }
  149. makeTooltip() {
  150. this.container = $.create('div', {
  151. inside: this.parent,
  152. className: 'graph-svg-tip comparison',
  153. innerHTML: `<span class="title"></span>
  154. <ul class="data-point-list"></ul>
  155. <div class="svg-pointer"></div>`
  156. });
  157. this.hideTip();
  158. this.title = this.container.querySelector('.title');
  159. this.dataPointList = this.container.querySelector('.data-point-list');
  160. this.parent.addEventListener('mouseleave', () => {
  161. this.hideTip();
  162. });
  163. }
  164. fill() {
  165. let title;
  166. if(this.index) {
  167. this.container.setAttribute('data-point-index', this.index);
  168. }
  169. if(this.titleValueFirst) {
  170. title = `<strong>${this.titleValue}</strong>${this.titleName}`;
  171. } else {
  172. title = `${this.titleName}<strong>${this.titleValue}</strong>`;
  173. }
  174. this.title.innerHTML = title;
  175. this.dataPointList.innerHTML = '';
  176. this.listValues.map((set, i) => {
  177. const color = this.colors[i] || 'black';
  178. let li = $.create('li', {
  179. styles: {
  180. 'border-top': `3px solid ${color}`
  181. },
  182. innerHTML: `<strong style="display: block;">${ set.value === 0 || set.value ? set.value : '' }</strong>
  183. ${set.title ? set.title : '' }`
  184. });
  185. this.dataPointList.appendChild(li);
  186. });
  187. }
  188. calcPosition() {
  189. let width = this.container.offsetWidth;
  190. this.top = this.y - this.container.offsetHeight
  191. - TOOLTIP_POINTER_TRIANGLE_HEIGHT;
  192. this.left = this.x - width/2;
  193. let maxLeft = this.parent.offsetWidth - width;
  194. let pointer = this.container.querySelector('.svg-pointer');
  195. if(this.left < 0) {
  196. pointer.style.left = `calc(50% - ${-1 * this.left}px)`;
  197. this.left = 0;
  198. } else if(this.left > maxLeft) {
  199. let delta = this.left - maxLeft;
  200. let pointerOffset = `calc(50% + ${delta}px)`;
  201. pointer.style.left = pointerOffset;
  202. this.left = maxLeft;
  203. } else {
  204. pointer.style.left = `50%`;
  205. }
  206. }
  207. setValues(x, y, title = {}, listValues = [], index = -1) {
  208. this.titleName = title.name;
  209. this.titleValue = title.value;
  210. this.listValues = listValues;
  211. this.x = x;
  212. this.y = y;
  213. this.titleValueFirst = title.valueFirst || 0;
  214. this.index = index;
  215. this.refresh();
  216. }
  217. hideTip() {
  218. this.container.style.top = '0px';
  219. this.container.style.left = '0px';
  220. this.container.style.opacity = '0';
  221. }
  222. showTip() {
  223. this.container.style.top = this.top + 'px';
  224. this.container.style.left = this.left + 'px';
  225. this.container.style.opacity = '1';
  226. }
  227. }
  228. function floatTwo(d) {
  229. return parseFloat(d.toFixed(2));
  230. }
  231. /**
  232. * Returns whether or not two given arrays are equal.
  233. * @param {Array} arr1 First array
  234. * @param {Array} arr2 Second array
  235. */
  236. /**
  237. * Shuffles array in place. ES6 version
  238. * @param {Array} array An array containing the items.
  239. */
  240. /**
  241. * Fill an array with extra points
  242. * @param {Array} array Array
  243. * @param {Number} count number of filler elements
  244. * @param {Object} element element to fill with
  245. * @param {Boolean} start fill at start?
  246. */
  247. function fillArray(array, count, element, start=false) {
  248. if(!element) {
  249. element = start ? array[0] : array[array.length - 1];
  250. }
  251. let fillerArray = new Array(Math.abs(count)).fill(element);
  252. array = start ? fillerArray.concat(array) : array.concat(fillerArray);
  253. return array;
  254. }
  255. /**
  256. * Returns pixel width of string.
  257. * @param {String} string
  258. * @param {Number} charWidth Width of single char in pixels
  259. */
  260. function getStringWidth(string, charWidth) {
  261. return (string+"").length * charWidth;
  262. }
  263. // https://stackoverflow.com/a/29325222
  264. function getPositionByAngle(angle, radius) {
  265. return {
  266. x: Math.sin(angle * ANGLE_RATIO) * radius,
  267. y: Math.cos(angle * ANGLE_RATIO) * radius,
  268. };
  269. }
  270. function getBarHeightAndYAttr(yTop, zeroLine) {
  271. let height, y;
  272. if (yTop <= zeroLine) {
  273. height = zeroLine - yTop;
  274. y = yTop;
  275. } else {
  276. height = yTop - zeroLine;
  277. y = zeroLine;
  278. }
  279. return [height, y];
  280. }
  281. function equilizeNoOfElements(array1, array2,
  282. extraCount = array2.length - array1.length) {
  283. // Doesn't work if either has zero elements.
  284. if(extraCount > 0) {
  285. array1 = fillArray(array1, extraCount);
  286. } else {
  287. array2 = fillArray(array2, extraCount);
  288. }
  289. return [array1, array2];
  290. }
  291. const PRESET_COLOR_MAP = {
  292. 'light-blue': '#7cd6fd',
  293. 'blue': '#5e64ff',
  294. 'violet': '#743ee2',
  295. 'red': '#ff5858',
  296. 'orange': '#ffa00a',
  297. 'yellow': '#feef72',
  298. 'green': '#28a745',
  299. 'light-green': '#98d85b',
  300. 'purple': '#b554ff',
  301. 'magenta': '#ffa3ef',
  302. 'black': '#36114C',
  303. 'grey': '#bdd3e6',
  304. 'light-grey': '#f0f4f7',
  305. 'dark-grey': '#b8c2cc'
  306. };
  307. function limitColor(r){
  308. if (r > 255) return 255;
  309. else if (r < 0) return 0;
  310. return r;
  311. }
  312. function lightenDarkenColor(color, amt) {
  313. let col = getColor(color);
  314. let usePound = false;
  315. if (col[0] == "#") {
  316. col = col.slice(1);
  317. usePound = true;
  318. }
  319. let num = parseInt(col,16);
  320. let r = limitColor((num >> 16) + amt);
  321. let b = limitColor(((num >> 8) & 0x00FF) + amt);
  322. let g = limitColor((num & 0x0000FF) + amt);
  323. return (usePound?"#":"") + (g | (b << 8) | (r << 16)).toString(16);
  324. }
  325. function isValidColor(string) {
  326. // https://stackoverflow.com/a/8027444/6495043
  327. return /(^#[0-9A-F]{6}$)|(^#[0-9A-F]{3}$)/i.test(string);
  328. }
  329. const getColor = (color) => {
  330. return PRESET_COLOR_MAP[color] || color;
  331. };
  332. const AXIS_TICK_LENGTH = 6;
  333. const LABEL_MARGIN = 4;
  334. const FONT_SIZE = 10;
  335. const BASE_LINE_COLOR = '#dadada';
  336. const FONT_FILL = '#555b51';
  337. function $$1(expr, con) {
  338. return typeof expr === "string"? (con || document).querySelector(expr) : expr || null;
  339. }
  340. function createSVG(tag, o) {
  341. var element = document.createElementNS("http://www.w3.org/2000/svg", tag);
  342. for (var i in o) {
  343. var val = o[i];
  344. if (i === "inside") {
  345. $$1(val).appendChild(element);
  346. }
  347. else if (i === "around") {
  348. var ref = $$1(val);
  349. ref.parentNode.insertBefore(element, ref);
  350. element.appendChild(ref);
  351. } else if (i === "styles") {
  352. if(typeof val === "object") {
  353. Object.keys(val).map(prop => {
  354. element.style[prop] = val[prop];
  355. });
  356. }
  357. } else {
  358. if(i === "className") { i = "class"; }
  359. if(i === "innerHTML") {
  360. element['textContent'] = val;
  361. } else {
  362. element.setAttribute(i, val);
  363. }
  364. }
  365. }
  366. return element;
  367. }
  368. function renderVerticalGradient(svgDefElem, gradientId) {
  369. return createSVG('linearGradient', {
  370. inside: svgDefElem,
  371. id: gradientId,
  372. x1: 0,
  373. x2: 0,
  374. y1: 0,
  375. y2: 1
  376. });
  377. }
  378. function setGradientStop(gradElem, offset, color, opacity) {
  379. return createSVG('stop', {
  380. 'inside': gradElem,
  381. 'style': `stop-color: ${color}`,
  382. 'offset': offset,
  383. 'stop-opacity': opacity
  384. });
  385. }
  386. function makeSVGContainer(parent, className, width, height) {
  387. return createSVG('svg', {
  388. className: className,
  389. inside: parent,
  390. width: width,
  391. height: height
  392. });
  393. }
  394. function makeSVGDefs(svgContainer) {
  395. return createSVG('defs', {
  396. inside: svgContainer,
  397. });
  398. }
  399. function makeSVGGroup(className, transform='', parent=undefined) {
  400. let args = {
  401. className: className,
  402. transform: transform
  403. };
  404. if(parent) args.inside = parent;
  405. return createSVG('g', args);
  406. }
  407. function makePath(pathStr, className='', stroke='none', fill='none') {
  408. return createSVG('path', {
  409. className: className,
  410. d: pathStr,
  411. styles: {
  412. stroke: stroke,
  413. fill: fill
  414. }
  415. });
  416. }
  417. function makeArcPathStr(startPosition, endPosition, center, radius, clockWise=1){
  418. let [arcStartX, arcStartY] = [center.x + startPosition.x, center.y + startPosition.y];
  419. let [arcEndX, arcEndY] = [center.x + endPosition.x, center.y + endPosition.y];
  420. return `M${center.x} ${center.y}
  421. L${arcStartX} ${arcStartY}
  422. A ${radius} ${radius} 0 0 ${clockWise ? 1 : 0}
  423. ${arcEndX} ${arcEndY} z`;
  424. }
  425. function makeGradient(svgDefElem, color, lighter = false) {
  426. let gradientId ='path-fill-gradient' + '-' + color + '-' +(lighter ? 'lighter' : 'default');
  427. let gradientDef = renderVerticalGradient(svgDefElem, gradientId);
  428. let opacities = [1, 0.6, 0.2];
  429. if(lighter) {
  430. opacities = [0.4, 0.2, 0];
  431. }
  432. setGradientStop(gradientDef, "0%", color, opacities[0]);
  433. setGradientStop(gradientDef, "50%", color, opacities[1]);
  434. setGradientStop(gradientDef, "100%", color, opacities[2]);
  435. return gradientId;
  436. }
  437. function percentageBar(x, y, width, height,
  438. depth=PERCENTAGE_BAR_DEFAULT_DEPTH, fill='none') {
  439. let args = {
  440. className: 'percentage-bar',
  441. x: x,
  442. y: y,
  443. width: width,
  444. height: height,
  445. fill: fill,
  446. styles: {
  447. 'stroke': lightenDarkenColor(fill, -25),
  448. // Diabolically good: https://stackoverflow.com/a/9000859
  449. // https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/stroke-dasharray
  450. 'stroke-dasharray': `0, ${height + width}, ${width}, ${height}`,
  451. 'stroke-width': depth
  452. },
  453. };
  454. return createSVG("rect", args);
  455. }
  456. function heatSquare(className, x, y, size, fill='none', data={}) {
  457. let args = {
  458. className: className,
  459. x: x,
  460. y: y,
  461. width: size,
  462. height: size,
  463. fill: fill
  464. };
  465. Object.keys(data).map(key => {
  466. args[key] = data[key];
  467. });
  468. return createSVG("rect", args);
  469. }
  470. function legendBar(x, y, size, fill='none', label) {
  471. let args = {
  472. className: 'legend-bar',
  473. x: 0,
  474. y: 0,
  475. width: size,
  476. height: '2px',
  477. fill: fill
  478. };
  479. let text = createSVG('text', {
  480. className: 'legend-dataset-text',
  481. x: 0,
  482. y: 0,
  483. dy: (FONT_SIZE * 2) + 'px',
  484. 'font-size': (FONT_SIZE * 1.2) + 'px',
  485. 'text-anchor': 'start',
  486. fill: FONT_FILL,
  487. innerHTML: label
  488. });
  489. let group = createSVG('g', {
  490. transform: `translate(${x}, ${y})`
  491. });
  492. group.appendChild(createSVG("rect", args));
  493. group.appendChild(text);
  494. return group;
  495. }
  496. function legendDot(x, y, size, fill='none', label) {
  497. let args = {
  498. className: 'legend-dot',
  499. cx: 0,
  500. cy: 0,
  501. r: size,
  502. fill: fill
  503. };
  504. let text = createSVG('text', {
  505. className: 'legend-dataset-text',
  506. x: 0,
  507. y: 0,
  508. dx: (FONT_SIZE) + 'px',
  509. dy: (FONT_SIZE/3) + 'px',
  510. 'font-size': (FONT_SIZE * 1.2) + 'px',
  511. 'text-anchor': 'start',
  512. fill: FONT_FILL,
  513. innerHTML: label
  514. });
  515. let group = createSVG('g', {
  516. transform: `translate(${x}, ${y})`
  517. });
  518. group.appendChild(createSVG("circle", args));
  519. group.appendChild(text);
  520. return group;
  521. }
  522. function makeText(className, x, y, content, options = {}) {
  523. let fontSize = options.fontSize || FONT_SIZE;
  524. let dy = options.dy !== undefined ? options.dy : (fontSize / 2);
  525. let fill = options.fill || FONT_FILL;
  526. let textAnchor = options.textAnchor || 'start';
  527. return createSVG('text', {
  528. className: className,
  529. x: x,
  530. y: y,
  531. dy: dy + 'px',
  532. 'font-size': fontSize + 'px',
  533. fill: fill,
  534. 'text-anchor': textAnchor,
  535. innerHTML: content
  536. });
  537. }
  538. function makeVertLine(x, label, y1, y2, options={}) {
  539. if(!options.stroke) options.stroke = BASE_LINE_COLOR;
  540. let l = createSVG('line', {
  541. className: 'line-vertical ' + options.className,
  542. x1: 0,
  543. x2: 0,
  544. y1: y1,
  545. y2: y2,
  546. styles: {
  547. stroke: options.stroke
  548. }
  549. });
  550. let text = createSVG('text', {
  551. x: 0,
  552. y: y1 > y2 ? y1 + LABEL_MARGIN : y1 - LABEL_MARGIN - FONT_SIZE,
  553. dy: FONT_SIZE + 'px',
  554. 'font-size': FONT_SIZE + 'px',
  555. 'text-anchor': 'middle',
  556. innerHTML: label + ""
  557. });
  558. let line = createSVG('g', {
  559. transform: `translate(${ x }, 0)`
  560. });
  561. line.appendChild(l);
  562. line.appendChild(text);
  563. return line;
  564. }
  565. function makeHoriLine(y, label, x1, x2, options={}) {
  566. if(!options.stroke) options.stroke = BASE_LINE_COLOR;
  567. if(!options.lineType) options.lineType = '';
  568. let className = 'line-horizontal ' + options.className +
  569. (options.lineType === "dashed" ? "dashed": "");
  570. let l = createSVG('line', {
  571. className: className,
  572. x1: x1,
  573. x2: x2,
  574. y1: 0,
  575. y2: 0,
  576. styles: {
  577. stroke: options.stroke
  578. }
  579. });
  580. let text = createSVG('text', {
  581. x: x1 < x2 ? x1 - LABEL_MARGIN : x1 + LABEL_MARGIN,
  582. y: 0,
  583. dy: (FONT_SIZE / 2 - 2) + 'px',
  584. 'font-size': FONT_SIZE + 'px',
  585. 'text-anchor': x1 < x2 ? 'end' : 'start',
  586. innerHTML: label+""
  587. });
  588. let line = createSVG('g', {
  589. transform: `translate(0, ${y})`,
  590. 'stroke-opacity': 1
  591. });
  592. if(text === 0 || text === '0') {
  593. line.style.stroke = "rgba(27, 31, 35, 0.6)";
  594. }
  595. line.appendChild(l);
  596. line.appendChild(text);
  597. return line;
  598. }
  599. function yLine(y, label, width, options={}) {
  600. if(!options.pos) options.pos = 'left';
  601. if(!options.offset) options.offset = 0;
  602. if(!options.mode) options.mode = 'span';
  603. if(!options.stroke) options.stroke = BASE_LINE_COLOR;
  604. if(!options.className) options.className = '';
  605. let x1 = -1 * AXIS_TICK_LENGTH;
  606. let x2 = options.mode === 'span' ? width + AXIS_TICK_LENGTH : 0;
  607. if(options.mode === 'tick' && options.pos === 'right') {
  608. x1 = width + AXIS_TICK_LENGTH;
  609. x2 = width;
  610. }
  611. // let offset = options.pos === 'left' ? -1 * options.offset : options.offset;
  612. x1 += options.offset;
  613. x2 += options.offset;
  614. return makeHoriLine(y, label, x1, x2, {
  615. stroke: options.stroke,
  616. className: options.className,
  617. lineType: options.lineType
  618. });
  619. }
  620. function xLine(x, label, height, options={}) {
  621. if(!options.pos) options.pos = 'bottom';
  622. if(!options.offset) options.offset = 0;
  623. if(!options.mode) options.mode = 'span';
  624. if(!options.stroke) options.stroke = BASE_LINE_COLOR;
  625. if(!options.className) options.className = '';
  626. // Draw X axis line in span/tick mode with optional label
  627. // y2(span)
  628. // |
  629. // |
  630. // x line |
  631. // |
  632. // |
  633. // ---------------------+-- y2(tick)
  634. // |
  635. // y1
  636. let y1 = height + AXIS_TICK_LENGTH;
  637. let y2 = options.mode === 'span' ? -1 * AXIS_TICK_LENGTH : height;
  638. if(options.mode === 'tick' && options.pos === 'top') {
  639. // top axis ticks
  640. y1 = -1 * AXIS_TICK_LENGTH;
  641. y2 = 0;
  642. }
  643. return makeVertLine(x, label, y1, y2, {
  644. stroke: options.stroke,
  645. className: options.className,
  646. lineType: options.lineType
  647. });
  648. }
  649. function yMarker(y, label, width, options={}) {
  650. let labelSvg = createSVG('text', {
  651. className: 'chart-label',
  652. x: width - getStringWidth(label, 5) - LABEL_MARGIN,
  653. y: 0,
  654. dy: (FONT_SIZE / -2) + 'px',
  655. 'font-size': FONT_SIZE + 'px',
  656. 'text-anchor': 'start',
  657. innerHTML: label+""
  658. });
  659. let line = makeHoriLine(y, '', 0, width, {
  660. stroke: options.stroke || BASE_LINE_COLOR,
  661. className: options.className || '',
  662. lineType: options.lineType
  663. });
  664. line.appendChild(labelSvg);
  665. return line;
  666. }
  667. function yRegion(y1, y2, width, label) {
  668. // return a group
  669. let height = y1 - y2;
  670. let rect = createSVG('rect', {
  671. className: `bar mini`, // remove class
  672. styles: {
  673. fill: `rgba(228, 234, 239, 0.49)`,
  674. stroke: BASE_LINE_COLOR,
  675. 'stroke-dasharray': `${width}, ${height}`
  676. },
  677. // 'data-point-index': index,
  678. x: 0,
  679. y: 0,
  680. width: width,
  681. height: height
  682. });
  683. let labelSvg = createSVG('text', {
  684. className: 'chart-label',
  685. x: width - getStringWidth(label+"", 4.5) - LABEL_MARGIN,
  686. y: 0,
  687. dy: (FONT_SIZE / -2) + 'px',
  688. 'font-size': FONT_SIZE + 'px',
  689. 'text-anchor': 'start',
  690. innerHTML: label+""
  691. });
  692. let region = createSVG('g', {
  693. transform: `translate(0, ${y2})`
  694. });
  695. region.appendChild(rect);
  696. region.appendChild(labelSvg);
  697. return region;
  698. }
  699. function datasetBar(x, yTop, width, color, label='', index=0, offset=0, meta={}) {
  700. let [height, y] = getBarHeightAndYAttr(yTop, meta.zeroLine);
  701. y -= offset;
  702. let rect = createSVG('rect', {
  703. className: `bar mini`,
  704. style: `fill: ${color}`,
  705. 'data-point-index': index,
  706. x: x,
  707. y: y,
  708. width: width,
  709. height: height || meta.minHeight // TODO: correct y for positive min height
  710. });
  711. label += "";
  712. if(!label && !label.length) {
  713. return rect;
  714. } else {
  715. rect.setAttribute('y', 0);
  716. rect.setAttribute('x', 0);
  717. let text = createSVG('text', {
  718. className: 'data-point-value',
  719. x: width/2,
  720. y: 0,
  721. dy: (FONT_SIZE / 2 * -1) + 'px',
  722. 'font-size': FONT_SIZE + 'px',
  723. 'text-anchor': 'middle',
  724. innerHTML: label
  725. });
  726. let group = createSVG('g', {
  727. 'data-point-index': index,
  728. transform: `translate(${x}, ${y})`
  729. });
  730. group.appendChild(rect);
  731. group.appendChild(text);
  732. return group;
  733. }
  734. }
  735. function datasetDot(x, y, radius, color, label='', index=0) {
  736. let dot = createSVG('circle', {
  737. style: `fill: ${color}`,
  738. 'data-point-index': index,
  739. cx: x,
  740. cy: y,
  741. r: radius
  742. });
  743. label += "";
  744. if(!label && !label.length) {
  745. return dot;
  746. } else {
  747. dot.setAttribute('cy', 0);
  748. dot.setAttribute('cx', 0);
  749. let text = createSVG('text', {
  750. className: 'data-point-value',
  751. x: 0,
  752. y: 0,
  753. dy: (FONT_SIZE / 2 * -1 - radius) + 'px',
  754. 'font-size': FONT_SIZE + 'px',
  755. 'text-anchor': 'middle',
  756. innerHTML: label
  757. });
  758. let group = createSVG('g', {
  759. 'data-point-index': index,
  760. transform: `translate(${x}, ${y})`
  761. });
  762. group.appendChild(dot);
  763. group.appendChild(text);
  764. return group;
  765. }
  766. }
  767. function getPaths(xList, yList, color, options={}, meta={}) {
  768. let pointsList = yList.map((y, i) => (xList[i] + ',' + y));
  769. let pointsStr = pointsList.join("L");
  770. let path = makePath("M"+pointsStr, 'line-graph-path', color);
  771. // HeatLine
  772. if(options.heatline) {
  773. let gradient_id = makeGradient(meta.svgDefs, color);
  774. path.style.stroke = `url(#${gradient_id})`;
  775. }
  776. let paths = {
  777. path: path
  778. };
  779. // Region
  780. if(options.regionFill) {
  781. let gradient_id_region = makeGradient(meta.svgDefs, color, true);
  782. // TODO: use zeroLine OR minimum
  783. let pathStr = "M" + `${xList[0]},${meta.zeroLine}L` + pointsStr + `L${xList.slice(-1)[0]},${meta.zeroLine}`;
  784. paths.region = makePath(pathStr, `region-fill`, 'none', `url(#${gradient_id_region})`);
  785. }
  786. return paths;
  787. }
  788. let makeOverlay = {
  789. 'bar': (unit) => {
  790. let transformValue;
  791. if(unit.nodeName !== 'rect') {
  792. transformValue = unit.getAttribute('transform');
  793. unit = unit.childNodes[0];
  794. }
  795. let overlay = unit.cloneNode();
  796. overlay.style.fill = '#000000';
  797. overlay.style.opacity = '0.4';
  798. if(transformValue) {
  799. overlay.setAttribute('transform', transformValue);
  800. }
  801. return overlay;
  802. },
  803. 'dot': (unit) => {
  804. let transformValue;
  805. if(unit.nodeName !== 'circle') {
  806. transformValue = unit.getAttribute('transform');
  807. unit = unit.childNodes[0];
  808. }
  809. let overlay = unit.cloneNode();
  810. let radius = unit.getAttribute('r');
  811. let fill = unit.getAttribute('fill');
  812. overlay.setAttribute('r', parseInt(radius) + DOT_OVERLAY_SIZE_INCR);
  813. overlay.setAttribute('fill', fill);
  814. overlay.style.opacity = '0.6';
  815. if(transformValue) {
  816. overlay.setAttribute('transform', transformValue);
  817. }
  818. return overlay;
  819. },
  820. 'heat_square': (unit) => {
  821. let transformValue;
  822. if(unit.nodeName !== 'circle') {
  823. transformValue = unit.getAttribute('transform');
  824. unit = unit.childNodes[0];
  825. }
  826. let overlay = unit.cloneNode();
  827. let radius = unit.getAttribute('r');
  828. let fill = unit.getAttribute('fill');
  829. overlay.setAttribute('r', parseInt(radius) + DOT_OVERLAY_SIZE_INCR);
  830. overlay.setAttribute('fill', fill);
  831. overlay.style.opacity = '0.6';
  832. if(transformValue) {
  833. overlay.setAttribute('transform', transformValue);
  834. }
  835. return overlay;
  836. }
  837. };
  838. let updateOverlay = {
  839. 'bar': (unit, overlay) => {
  840. let transformValue;
  841. if(unit.nodeName !== 'rect') {
  842. transformValue = unit.getAttribute('transform');
  843. unit = unit.childNodes[0];
  844. }
  845. let attributes = ['x', 'y', 'width', 'height'];
  846. Object.values(unit.attributes)
  847. .filter(attr => attributes.includes(attr.name) && attr.specified)
  848. .map(attr => {
  849. overlay.setAttribute(attr.name, attr.nodeValue);
  850. });
  851. if(transformValue) {
  852. overlay.setAttribute('transform', transformValue);
  853. }
  854. },
  855. 'dot': (unit, overlay) => {
  856. let transformValue;
  857. if(unit.nodeName !== 'circle') {
  858. transformValue = unit.getAttribute('transform');
  859. unit = unit.childNodes[0];
  860. }
  861. let attributes = ['cx', 'cy'];
  862. Object.values(unit.attributes)
  863. .filter(attr => attributes.includes(attr.name) && attr.specified)
  864. .map(attr => {
  865. overlay.setAttribute(attr.name, attr.nodeValue);
  866. });
  867. if(transformValue) {
  868. overlay.setAttribute('transform', transformValue);
  869. }
  870. },
  871. 'heat_square': (unit, overlay) => {
  872. let transformValue;
  873. if(unit.nodeName !== 'circle') {
  874. transformValue = unit.getAttribute('transform');
  875. unit = unit.childNodes[0];
  876. }
  877. let attributes = ['cx', 'cy'];
  878. Object.values(unit.attributes)
  879. .filter(attr => attributes.includes(attr.name) && attr.specified)
  880. .map(attr => {
  881. overlay.setAttribute(attr.name, attr.nodeValue);
  882. });
  883. if(transformValue) {
  884. overlay.setAttribute('transform', transformValue);
  885. }
  886. },
  887. };
  888. const UNIT_ANIM_DUR = 350;
  889. const PATH_ANIM_DUR = 350;
  890. const MARKER_LINE_ANIM_DUR = UNIT_ANIM_DUR;
  891. const REPLACE_ALL_NEW_DUR = 250;
  892. const STD_EASING = 'easein';
  893. function translate(unit, oldCoord, newCoord, duration) {
  894. let old = typeof oldCoord === 'string' ? oldCoord : oldCoord.join(', ');
  895. return [
  896. unit,
  897. {transform: newCoord.join(', ')},
  898. duration,
  899. STD_EASING,
  900. "translate",
  901. {transform: old}
  902. ];
  903. }
  904. function translateVertLine(xLine, newX, oldX) {
  905. return translate(xLine, [oldX, 0], [newX, 0], MARKER_LINE_ANIM_DUR);
  906. }
  907. function translateHoriLine(yLine, newY, oldY) {
  908. return translate(yLine, [0, oldY], [0, newY], MARKER_LINE_ANIM_DUR);
  909. }
  910. function animateRegion(rectGroup, newY1, newY2, oldY2) {
  911. let newHeight = newY1 - newY2;
  912. let rect = rectGroup.childNodes[0];
  913. let width = rect.getAttribute("width");
  914. let rectAnim = [
  915. rect,
  916. { height: newHeight, 'stroke-dasharray': `${width}, ${newHeight}` },
  917. MARKER_LINE_ANIM_DUR,
  918. STD_EASING
  919. ];
  920. let groupAnim = translate(rectGroup, [0, oldY2], [0, newY2], MARKER_LINE_ANIM_DUR);
  921. return [rectAnim, groupAnim];
  922. }
  923. function animateBar(bar, x, yTop, width, offset=0, meta={}) {
  924. let [height, y] = getBarHeightAndYAttr(yTop, meta.zeroLine);
  925. y -= offset;
  926. if(bar.nodeName !== 'rect') {
  927. let rect = bar.childNodes[0];
  928. let rectAnim = [
  929. rect,
  930. {width: width, height: height},
  931. UNIT_ANIM_DUR,
  932. STD_EASING
  933. ];
  934. let oldCoordStr = bar.getAttribute("transform").split("(")[1].slice(0, -1);
  935. let groupAnim = translate(bar, oldCoordStr, [x, y], MARKER_LINE_ANIM_DUR);
  936. return [rectAnim, groupAnim];
  937. } else {
  938. return [[bar, {width: width, height: height, x: x, y: y}, UNIT_ANIM_DUR, STD_EASING]];
  939. }
  940. // bar.animate({height: args.newHeight, y: yTop}, UNIT_ANIM_DUR, mina.easein);
  941. }
  942. function animateDot(dot, x, y) {
  943. if(dot.nodeName !== 'circle') {
  944. let oldCoordStr = dot.getAttribute("transform").split("(")[1].slice(0, -1);
  945. let groupAnim = translate(dot, oldCoordStr, [x, y], MARKER_LINE_ANIM_DUR);
  946. return [groupAnim];
  947. } else {
  948. return [[dot, {cx: x, cy: y}, UNIT_ANIM_DUR, STD_EASING]];
  949. }
  950. // dot.animate({cy: yTop}, UNIT_ANIM_DUR, mina.easein);
  951. }
  952. function animatePath(paths, newXList, newYList, zeroLine) {
  953. let pathComponents = [];
  954. let pointsStr = newYList.map((y, i) => (newXList[i] + ',' + y));
  955. let pathStr = pointsStr.join("L");
  956. const animPath = [paths.path, {d:"M"+pathStr}, PATH_ANIM_DUR, STD_EASING];
  957. pathComponents.push(animPath);
  958. if(paths.region) {
  959. let regStartPt = `${newXList[0]},${zeroLine}L`;
  960. let regEndPt = `L${newXList.slice(-1)[0]}, ${zeroLine}`;
  961. const animRegion = [
  962. paths.region,
  963. {d:"M" + regStartPt + pathStr + regEndPt},
  964. PATH_ANIM_DUR,
  965. STD_EASING
  966. ];
  967. pathComponents.push(animRegion);
  968. }
  969. return pathComponents;
  970. }
  971. function animatePathStr(oldPath, pathStr) {
  972. return [oldPath, {d: pathStr}, UNIT_ANIM_DUR, STD_EASING];
  973. }
  974. // Leveraging SMIL Animations
  975. const EASING = {
  976. ease: "0.25 0.1 0.25 1",
  977. linear: "0 0 1 1",
  978. // easein: "0.42 0 1 1",
  979. easein: "0.1 0.8 0.2 1",
  980. easeout: "0 0 0.58 1",
  981. easeinout: "0.42 0 0.58 1"
  982. };
  983. function animateSVGElement(element, props, dur, easingType="linear", type=undefined, oldValues={}) {
  984. let animElement = element.cloneNode(true);
  985. let newElement = element.cloneNode(true);
  986. for(var attributeName in props) {
  987. let animateElement;
  988. if(attributeName === 'transform') {
  989. animateElement = document.createElementNS("http://www.w3.org/2000/svg", "animateTransform");
  990. } else {
  991. animateElement = document.createElementNS("http://www.w3.org/2000/svg", "animate");
  992. }
  993. let currentValue = oldValues[attributeName] || element.getAttribute(attributeName);
  994. let value = props[attributeName];
  995. let animAttr = {
  996. attributeName: attributeName,
  997. from: currentValue,
  998. to: value,
  999. begin: "0s",
  1000. dur: dur/1000 + "s",
  1001. values: currentValue + ";" + value,
  1002. keySplines: EASING[easingType],
  1003. keyTimes: "0;1",
  1004. calcMode: "spline",
  1005. fill: 'freeze'
  1006. };
  1007. if(type) {
  1008. animAttr["type"] = type;
  1009. }
  1010. for (var i in animAttr) {
  1011. animateElement.setAttribute(i, animAttr[i]);
  1012. }
  1013. animElement.appendChild(animateElement);
  1014. if(type) {
  1015. newElement.setAttribute(attributeName, `translate(${value})`);
  1016. } else {
  1017. newElement.setAttribute(attributeName, value);
  1018. }
  1019. }
  1020. return [animElement, newElement];
  1021. }
  1022. function transform(element, style) { // eslint-disable-line no-unused-vars
  1023. element.style.transform = style;
  1024. element.style.webkitTransform = style;
  1025. element.style.msTransform = style;
  1026. element.style.mozTransform = style;
  1027. element.style.oTransform = style;
  1028. }
  1029. function animateSVG(svgContainer, elements) {
  1030. let newElements = [];
  1031. let animElements = [];
  1032. elements.map(element => {
  1033. let unit = element[0];
  1034. let parent = unit.parentNode;
  1035. let animElement, newElement;
  1036. element[0] = unit;
  1037. [animElement, newElement] = animateSVGElement(...element);
  1038. newElements.push(newElement);
  1039. animElements.push([animElement, parent]);
  1040. parent.replaceChild(animElement, unit);
  1041. });
  1042. let animSvg = svgContainer.cloneNode(true);
  1043. animElements.map((animElement, i) => {
  1044. animElement[1].replaceChild(newElements[i], animElement[0]);
  1045. elements[i][0] = newElements[i];
  1046. });
  1047. return animSvg;
  1048. }
  1049. function runSMILAnimation(parent, svgElement, elementsToAnimate) {
  1050. if(elementsToAnimate.length === 0) return;
  1051. let animSvgElement = animateSVG(svgElement, elementsToAnimate);
  1052. if(svgElement.parentNode == parent) {
  1053. parent.removeChild(svgElement);
  1054. parent.appendChild(animSvgElement);
  1055. }
  1056. // Replace the new svgElement (data has already been replaced)
  1057. setTimeout(() => {
  1058. if(animSvgElement.parentNode == parent) {
  1059. parent.removeChild(animSvgElement);
  1060. parent.appendChild(svgElement);
  1061. }
  1062. }, REPLACE_ALL_NEW_DUR);
  1063. }
  1064. const CSSTEXT = ".chart-container{position:relative;font-family:-apple-system,BlinkMacSystemFont,'Segoe UI','Roboto','Oxygen','Ubuntu','Cantarell','Fira Sans','Droid Sans','Helvetica Neue',sans-serif}.chart-container .axis,.chart-container .chart-label{fill:#555b51}.chart-container .axis line,.chart-container .chart-label line{stroke:#dadada}.chart-container .dataset-units circle{stroke:#fff;stroke-width:2}.chart-container .dataset-units path{fill:none;stroke-opacity:1;stroke-width:2px}.chart-container .dataset-path{stroke-width:2px}.chart-container .path-group path{fill:none;stroke-opacity:1;stroke-width:2px}.chart-container line.dashed{stroke-dasharray:5,3}.chart-container .axis-line .specific-value{text-anchor:start}.chart-container .axis-line .y-line{text-anchor:end}.chart-container .axis-line .x-line{text-anchor:middle}.graph-svg-tip{position:absolute;z-index:99999;padding:10px;font-size:12px;color:#959da5;text-align:center;background:rgba(0,0,0,.8);border-radius:3px}.graph-svg-tip ul{padding-left:0;display:flex}.graph-svg-tip ol{padding-left:0;display:flex}.graph-svg-tip ul.data-point-list li{min-width:90px;flex:1;font-weight:600}.graph-svg-tip strong{color:#dfe2e5;font-weight:600}.graph-svg-tip .svg-pointer{position:absolute;height:5px;margin:0 0 0 -5px;content:' ';border:5px solid transparent;border-top-color:rgba(0,0,0,.8)}.graph-svg-tip.comparison{padding:0;text-align:left;pointer-events:none}.graph-svg-tip.comparison .title{display:block;padding:10px;margin:0;font-weight:600;line-height:1;pointer-events:none}.graph-svg-tip.comparison ul{margin:0;white-space:nowrap;list-style:none}.graph-svg-tip.comparison li{display:inline-block;padding:5px 10px}";
  1065. function downloadFile(filename, data) {
  1066. var a = document.createElement('a');
  1067. a.style = "display: none";
  1068. var blob = new Blob(data, {type: "image/svg+xml; charset=utf-8"});
  1069. var url = window.URL.createObjectURL(blob);
  1070. a.href = url;
  1071. a.download = filename;
  1072. document.body.appendChild(a);
  1073. a.click();
  1074. setTimeout(function(){
  1075. document.body.removeChild(a);
  1076. window.URL.revokeObjectURL(url);
  1077. }, 300);
  1078. }
  1079. function prepareForExport(svg) {
  1080. let clone = svg.cloneNode(true);
  1081. clone.classList.add('chart-container');
  1082. clone.setAttribute('xmlns', "http://www.w3.org/2000/svg");
  1083. clone.setAttribute('xmlns:xlink', "http://www.w3.org/1999/xlink");
  1084. let styleEl = $.create('style', {
  1085. 'innerHTML': CSSTEXT
  1086. });
  1087. clone.insertBefore(styleEl, clone.firstChild);
  1088. let container = $.create('div');
  1089. container.appendChild(clone);
  1090. return container.innerHTML;
  1091. }
  1092. class BaseChart {
  1093. constructor(parent, options) {
  1094. this.parent = typeof parent === 'string'
  1095. ? document.querySelector(parent)
  1096. : parent;
  1097. if (!(this.parent instanceof HTMLElement)) {
  1098. throw new Error('No `parent` element to render on was provided.');
  1099. }
  1100. this.rawChartArgs = options;
  1101. this.title = options.title || '';
  1102. this.type = options.type || '';
  1103. this.realData = this.prepareData(options.data);
  1104. this.data = this.prepareFirstData(this.realData);
  1105. this.colors = this.validateColors(options.colors, this.type);
  1106. this.config = {
  1107. showTooltip: 1, // calculate
  1108. showLegend: 1, // calculate
  1109. isNavigable: options.isNavigable || 0,
  1110. animate: 1
  1111. };
  1112. this.measures = JSON.parse(JSON.stringify(BASE_MEASURES));
  1113. let m = this.measures;
  1114. this.setMeasures(options);
  1115. if(!this.title.length) { m.titleHeight = 0; }
  1116. if(!this.config.showLegend) m.legendHeight = 0;
  1117. this.argHeight = options.height || m.baseHeight;
  1118. this.state = {};
  1119. this.options = {};
  1120. this.initTimeout = INIT_CHART_UPDATE_TIMEOUT;
  1121. if(this.config.isNavigable) {
  1122. this.overlays = [];
  1123. }
  1124. this.configure(options);
  1125. }
  1126. prepareData(data) {
  1127. return data;
  1128. }
  1129. prepareFirstData(data) {
  1130. return data;
  1131. }
  1132. validateColors(colors, type) {
  1133. const validColors = [];
  1134. colors = (colors || []).concat(DEFAULT_COLORS[type]);
  1135. colors.forEach((string) => {
  1136. const color = getColor(string);
  1137. if(!isValidColor(color)) {
  1138. console.warn('"' + string + '" is not a valid color.');
  1139. } else {
  1140. validColors.push(color);
  1141. }
  1142. });
  1143. return validColors;
  1144. }
  1145. setMeasures() {
  1146. // Override measures, including those for title and legend
  1147. // set config for legend and title
  1148. }
  1149. configure() {
  1150. let height = this.argHeight;
  1151. this.baseHeight = height;
  1152. this.height = height - getExtraHeight(this.measures);
  1153. // Bind window events
  1154. window.addEventListener('resize', () => this.draw(true));
  1155. window.addEventListener('orientationchange', () => this.draw(true));
  1156. }
  1157. // Has to be called manually
  1158. setup() {
  1159. this.makeContainer();
  1160. this.updateWidth();
  1161. this.makeTooltip();
  1162. this.draw(false, true);
  1163. }
  1164. makeContainer() {
  1165. // Chart needs a dedicated parent element
  1166. this.parent.innerHTML = '';
  1167. let args = {
  1168. inside: this.parent,
  1169. className: 'chart-container'
  1170. };
  1171. if(this.independentWidth) {
  1172. args.styles = { width: this.independentWidth + 'px' };
  1173. }
  1174. this.container = $.create('div', args);
  1175. }
  1176. makeTooltip() {
  1177. this.tip = new SvgTip({
  1178. parent: this.container,
  1179. colors: this.colors
  1180. });
  1181. this.bindTooltip();
  1182. }
  1183. bindTooltip() {}
  1184. draw(onlyWidthChange=false, init=false) {
  1185. this.calc(onlyWidthChange);
  1186. this.updateWidth();
  1187. this.makeChartArea();
  1188. this.setupComponents();
  1189. this.components.forEach(c => c.setup(this.drawArea));
  1190. // this.components.forEach(c => c.make());
  1191. this.render(this.components, false);
  1192. if(init) {
  1193. this.data = this.realData;
  1194. setTimeout(() => {this.update(this.data);}, this.initTimeout);
  1195. }
  1196. this.renderLegend();
  1197. this.setupNavigation(init);
  1198. }
  1199. calc() {} // builds state
  1200. updateWidth() {
  1201. this.baseWidth = getElementContentWidth(this.parent);
  1202. this.width = this.baseWidth - getExtraWidth(this.measures);
  1203. }
  1204. makeChartArea() {
  1205. if(this.svg) {
  1206. this.container.removeChild(this.svg);
  1207. }
  1208. let m = this.measures;
  1209. this.svg = makeSVGContainer(
  1210. this.container,
  1211. 'frappe-chart chart',
  1212. this.baseWidth,
  1213. this.baseHeight
  1214. );
  1215. this.svgDefs = makeSVGDefs(this.svg);
  1216. if(this.title.length) {
  1217. this.titleEL = makeText(
  1218. 'title',
  1219. m.margins.left,
  1220. m.margins.top,
  1221. this.title,
  1222. {
  1223. fontSize: m.titleFontSize,
  1224. fill: '#666666',
  1225. dy: m.titleFontSize
  1226. }
  1227. );
  1228. }
  1229. let top = m.margins.top + m.titleHeight + m.paddings.top;
  1230. this.drawArea = makeSVGGroup(
  1231. this.type + '-chart chart-draw-area',
  1232. `translate(${m.margins.left + m.paddings.left}, ${top})`
  1233. );
  1234. if(this.config.showLegend) {
  1235. top += this.height + m.paddings.bottom;
  1236. this.legendArea = makeSVGGroup(
  1237. 'chart-legend',
  1238. `translate(${m.margins.left + m.paddings.left}, ${top})`
  1239. );
  1240. }
  1241. if(this.title.length) { this.svg.appendChild(this.titleEL); }
  1242. this.svg.appendChild(this.drawArea);
  1243. if(this.config.showLegend) { this.svg.appendChild(this.legendArea); }
  1244. this.updateTipOffset(m.margins.left + m.paddings.left, m.margins.top + m.paddings.top + m.titleHeight);
  1245. }
  1246. updateTipOffset(x, y) {
  1247. this.tip.offset = {
  1248. x: x,
  1249. y: y
  1250. };
  1251. }
  1252. setupComponents() { this.components = new Map(); }
  1253. update(data) {
  1254. if(!data) {
  1255. console.error('No data to update.');
  1256. }
  1257. this.data = this.prepareData(data);
  1258. this.calc(); // builds state
  1259. this.render();
  1260. }
  1261. render(components=this.components, animate=true) {
  1262. if(this.config.isNavigable) {
  1263. // Remove all existing overlays
  1264. this.overlays.map(o => o.parentNode.removeChild(o));
  1265. // ref.parentNode.insertBefore(element, ref);
  1266. }
  1267. let elementsToAnimate = [];
  1268. // Can decouple to this.refreshComponents() first to save animation timeout
  1269. components.forEach(c => {
  1270. elementsToAnimate = elementsToAnimate.concat(c.update(animate));
  1271. });
  1272. if(elementsToAnimate.length > 0) {
  1273. runSMILAnimation(this.container, this.svg, elementsToAnimate);
  1274. setTimeout(() => {
  1275. components.forEach(c => c.make());
  1276. this.updateNav();
  1277. }, CHART_POST_ANIMATE_TIMEOUT);
  1278. } else {
  1279. components.forEach(c => c.make());
  1280. this.updateNav();
  1281. }
  1282. }
  1283. updateNav() {
  1284. if(this.config.isNavigable) {
  1285. this.makeOverlay();
  1286. this.bindUnits();
  1287. }
  1288. }
  1289. renderLegend() {}
  1290. setupNavigation(init=false) {
  1291. if(!this.config.isNavigable) return;
  1292. if(init) {
  1293. this.bindOverlay();
  1294. this.keyActions = {
  1295. '13': this.onEnterKey.bind(this),
  1296. '37': this.onLeftArrow.bind(this),
  1297. '38': this.onUpArrow.bind(this),
  1298. '39': this.onRightArrow.bind(this),
  1299. '40': this.onDownArrow.bind(this),
  1300. };
  1301. document.addEventListener('keydown', (e) => {
  1302. if(isElementInViewport(this.container)) {
  1303. e = e || window.event;
  1304. if(this.keyActions[e.keyCode]) {
  1305. this.keyActions[e.keyCode]();
  1306. }
  1307. }
  1308. });
  1309. }
  1310. }
  1311. makeOverlay() {}
  1312. updateOverlay() {}
  1313. bindOverlay() {}
  1314. bindUnits() {}
  1315. onLeftArrow() {}
  1316. onRightArrow() {}
  1317. onUpArrow() {}
  1318. onDownArrow() {}
  1319. onEnterKey() {}
  1320. addDataPoint() {}
  1321. removeDataPoint() {}
  1322. getDataPoint() {}
  1323. setCurrentDataPoint() {}
  1324. updateDataset() {}
  1325. boundDrawFn() {
  1326. this.draw(true);
  1327. }
  1328. unbindWindowEvents(){
  1329. window.removeEventListener('resize', () => this.boundDrawFn.bind(this));
  1330. window.removeEventListener('orientationchange', () => this.boundDrawFn.bind(this));
  1331. }
  1332. export() {
  1333. let chartSvg = prepareForExport(this.svg);
  1334. downloadFile(this.title || 'Chart', [chartSvg]);
  1335. }
  1336. }
  1337. class AggregationChart extends BaseChart {
  1338. constructor(parent, args) {
  1339. super(parent, args);
  1340. }
  1341. configure(args) {
  1342. super.configure(args);
  1343. this.config.maxSlices = args.maxSlices || 20;
  1344. this.config.maxLegendPoints = args.maxLegendPoints || 20;
  1345. }
  1346. calc() {
  1347. let s = this.state;
  1348. let maxSlices = this.config.maxSlices;
  1349. s.sliceTotals = [];
  1350. let allTotals = this.data.labels.map((label, i) => {
  1351. let total = 0;
  1352. this.data.datasets.map(e => {
  1353. total += e.values[i];
  1354. });
  1355. return [total, label];
  1356. }).filter(d => { return d[0] > 0; }); // keep only positive results
  1357. let totals = allTotals;
  1358. if(allTotals.length > maxSlices) {
  1359. // Prune and keep a grey area for rest as per maxSlices
  1360. allTotals.sort((a, b) => { return b[0] - a[0]; });
  1361. totals = allTotals.slice(0, maxSlices-1);
  1362. let remaining = allTotals.slice(maxSlices-1);
  1363. let sumOfRemaining = 0;
  1364. remaining.map(d => {sumOfRemaining += d[0];});
  1365. totals.push([sumOfRemaining, 'Rest']);
  1366. this.colors[maxSlices-1] = 'grey';
  1367. }
  1368. s.labels = [];
  1369. totals.map(d => {
  1370. s.sliceTotals.push(d[0]);
  1371. s.labels.push(d[1]);
  1372. });
  1373. s.grandTotal = s.sliceTotals.reduce((a, b) => a + b, 0);
  1374. this.center = {
  1375. x: this.width / 2,
  1376. y: this.height / 2
  1377. };
  1378. }
  1379. renderLegend() {
  1380. let s = this.state;
  1381. this.legendArea.textContent = '';
  1382. this.legendTotals = s.sliceTotals.slice(0, this.config.maxLegendPoints);
  1383. this.legendTotals.map((d, i) => {
  1384. let barWidth = 110;
  1385. let rect = legendDot(
  1386. barWidth * i + 5,
  1387. '0',
  1388. 5,
  1389. this.colors[i],
  1390. `${s.labels[i]}: ${d}`
  1391. );
  1392. this.legendArea.appendChild(rect);
  1393. });
  1394. }
  1395. }
  1396. // Playing around with dates
  1397. const NO_OF_YEAR_MONTHS = 12;
  1398. const NO_OF_DAYS_IN_WEEK = 7;
  1399. const NO_OF_MILLIS = 1000;
  1400. const SEC_IN_DAY = 86400;
  1401. const MONTH_NAMES = ["January", "February", "March", "April", "May",
  1402. "June", "July", "August", "September", "October", "November", "December"];
  1403. const DAY_NAMES_SHORT = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
  1404. // https://stackoverflow.com/a/11252167/6495043
  1405. function treatAsUtc(date) {
  1406. let result = new Date(date);
  1407. result.setMinutes(result.getMinutes() - result.getTimezoneOffset());
  1408. return result;
  1409. }
  1410. function getYyyyMmDd(date) {
  1411. let dd = date.getDate();
  1412. let mm = date.getMonth() + 1; // getMonth() is zero-based
  1413. return [
  1414. date.getFullYear(),
  1415. (mm>9 ? '' : '0') + mm,
  1416. (dd>9 ? '' : '0') + dd
  1417. ].join('-');
  1418. }
  1419. function clone(date) {
  1420. return new Date(date.getTime());
  1421. }
  1422. // export function getMonthsBetween(startDate, endDate) {}
  1423. function getWeeksBetween(startDate, endDate) {
  1424. let weekStartDate = setDayToSunday(startDate);
  1425. return Math.ceil(getDaysBetween(weekStartDate, endDate) / NO_OF_DAYS_IN_WEEK);
  1426. }
  1427. function getDaysBetween(startDate, endDate) {
  1428. let millisecondsPerDay = SEC_IN_DAY * NO_OF_MILLIS;
  1429. return (treatAsUtc(endDate) - treatAsUtc(startDate)) / millisecondsPerDay;
  1430. }
  1431. function areInSameMonth(startDate, endDate) {
  1432. return startDate.getMonth() === endDate.getMonth()
  1433. && startDate.getFullYear() === endDate.getFullYear();
  1434. }
  1435. function getMonthName(i, short=false) {
  1436. let monthName = MONTH_NAMES[i];
  1437. return short ? monthName.slice(0, 3) : monthName;
  1438. }
  1439. function getLastDateInMonth (month, year) {
  1440. return new Date(year, month + 1, 0); // 0: last day in previous month
  1441. }
  1442. // mutates
  1443. function setDayToSunday(date) {
  1444. let newDate = clone(date);
  1445. const day = newDate.getDay();
  1446. if(day !== 0) {
  1447. addDays(newDate, (-1) * day);
  1448. }
  1449. return newDate;
  1450. }
  1451. // mutates
  1452. function addDays(date, numberOfDays) {
  1453. date.setDate(date.getDate() + numberOfDays);
  1454. }
  1455. class ChartComponent {
  1456. constructor({
  1457. layerClass = '',
  1458. layerTransform = '',
  1459. constants,
  1460. getData,
  1461. makeElements,
  1462. animateElements
  1463. }) {
  1464. this.layerTransform = layerTransform;
  1465. this.constants = constants;
  1466. this.makeElements = makeElements;
  1467. this.getData = getData;
  1468. this.animateElements = animateElements;
  1469. this.store = [];
  1470. this.labels = [];
  1471. this.layerClass = layerClass;
  1472. this.layerClass = typeof(this.layerClass) === 'function'
  1473. ? this.layerClass() : this.layerClass;
  1474. this.refresh();
  1475. }
  1476. refresh(data) {
  1477. this.data = data || this.getData();
  1478. }
  1479. setup(parent) {
  1480. this.layer = makeSVGGroup(this.layerClass, this.layerTransform, parent);
  1481. }
  1482. make() {
  1483. this.render(this.data);
  1484. this.oldData = this.data;
  1485. }
  1486. render(data) {
  1487. this.store = this.makeElements(data);
  1488. this.layer.textContent = '';
  1489. this.store.forEach(element => {
  1490. this.layer.appendChild(element);
  1491. });
  1492. this.labels.forEach(element => {
  1493. this.layer.appendChild(element);
  1494. });
  1495. }
  1496. update(animate = true) {
  1497. this.refresh();
  1498. let animateElements = [];
  1499. if(animate) {
  1500. animateElements = this.animateElements(this.data) || [];
  1501. }
  1502. return animateElements;
  1503. }
  1504. }
  1505. let componentConfigs = {
  1506. pieSlices: {
  1507. layerClass: 'pie-slices',
  1508. makeElements(data) {
  1509. return data.sliceStrings.map((s, i) =>{
  1510. let slice = makePath(s, 'pie-path', 'none', data.colors[i]);
  1511. slice.style.transition = 'transform .3s;';
  1512. return slice;
  1513. });
  1514. },
  1515. animateElements(newData) {
  1516. return this.store.map((slice, i) =>
  1517. animatePathStr(slice, newData.sliceStrings[i])
  1518. );
  1519. }
  1520. },
  1521. percentageBars: {
  1522. layerClass: 'percentage-bars',
  1523. makeElements(data) {
  1524. return data.xPositions.map((x, i) =>{
  1525. let y = 0;
  1526. let bar = percentageBar(x, y, data.widths[i],
  1527. this.constants.barHeight, this.constants.barDepth, data.colors[i]);
  1528. return bar;
  1529. });
  1530. },
  1531. animateElements(newData) {
  1532. if(newData) return [];
  1533. }
  1534. },
  1535. yAxis: {
  1536. layerClass: 'y axis',
  1537. makeElements(data) {
  1538. return data.positions.map((position, i) =>
  1539. yLine(position, data.labels[i], this.constants.width,
  1540. {mode: this.constants.mode, pos: this.constants.pos})
  1541. );
  1542. },
  1543. animateElements(newData) {
  1544. let newPos = newData.positions;
  1545. let newLabels = newData.labels;
  1546. let oldPos = this.oldData.positions;
  1547. let oldLabels = this.oldData.labels;
  1548. [oldPos, newPos] = equilizeNoOfElements(oldPos, newPos);
  1549. [oldLabels, newLabels] = equilizeNoOfElements(oldLabels, newLabels);
  1550. this.render({
  1551. positions: oldPos,
  1552. labels: newLabels
  1553. });
  1554. return this.store.map((line, i) => {
  1555. return translateHoriLine(
  1556. line, newPos[i], oldPos[i]
  1557. );
  1558. });
  1559. }
  1560. },
  1561. xAxis: {
  1562. layerClass: 'x axis',
  1563. makeElements(data) {
  1564. return data.positions.map((position, i) =>
  1565. xLine(position, data.calcLabels[i], this.constants.height,
  1566. {mode: this.constants.mode, pos: this.constants.pos})
  1567. );
  1568. },
  1569. animateElements(newData) {
  1570. let newPos = newData.positions;
  1571. let newLabels = newData.calcLabels;
  1572. let oldPos = this.oldData.positions;
  1573. let oldLabels = this.oldData.calcLabels;
  1574. [oldPos, newPos] = equilizeNoOfElements(oldPos, newPos);
  1575. [oldLabels, newLabels] = equilizeNoOfElements(oldLabels, newLabels);
  1576. this.render({
  1577. positions: oldPos,
  1578. calcLabels: newLabels
  1579. });
  1580. return this.store.map((line, i) => {
  1581. return translateVertLine(
  1582. line, newPos[i], oldPos[i]
  1583. );
  1584. });
  1585. }
  1586. },
  1587. yMarkers: {
  1588. layerClass: 'y-markers',
  1589. makeElements(data) {
  1590. return data.map(marker =>
  1591. yMarker(marker.position, marker.label, this.constants.width,
  1592. {pos:'right', mode: 'span', lineType: 'dashed'})
  1593. );
  1594. },
  1595. animateElements(newData) {
  1596. [this.oldData, newData] = equilizeNoOfElements(this.oldData, newData);
  1597. let newPos = newData.map(d => d.position);
  1598. let newLabels = newData.map(d => d.label);
  1599. let oldPos = this.oldData.map(d => d.position);
  1600. this.render(oldPos.map((pos, i) => {
  1601. return {
  1602. position: oldPos[i],
  1603. label: newLabels[i]
  1604. };
  1605. }));
  1606. return this.store.map((line, i) => {
  1607. return translateHoriLine(
  1608. line, newPos[i], oldPos[i]
  1609. );
  1610. });
  1611. }
  1612. },
  1613. yRegions: {
  1614. layerClass: 'y-regions',
  1615. makeElements(data) {
  1616. return data.map(region =>
  1617. yRegion(region.startPos, region.endPos, this.constants.width,
  1618. region.label)
  1619. );
  1620. },
  1621. animateElements(newData) {
  1622. [this.oldData, newData] = equilizeNoOfElements(this.oldData, newData);
  1623. let newPos = newData.map(d => d.endPos);
  1624. let newLabels = newData.map(d => d.label);
  1625. let newStarts = newData.map(d => d.startPos);
  1626. let oldPos = this.oldData.map(d => d.endPos);
  1627. let oldStarts = this.oldData.map(d => d.startPos);
  1628. this.render(oldPos.map((pos, i) => {
  1629. return {
  1630. startPos: oldStarts[i],
  1631. endPos: oldPos[i],
  1632. label: newLabels[i]
  1633. };
  1634. }));
  1635. let animateElements = [];
  1636. this.store.map((rectGroup, i) => {
  1637. animateElements = animateElements.concat(animateRegion(
  1638. rectGroup, newStarts[i], newPos[i], oldPos[i]
  1639. ));
  1640. });
  1641. return animateElements;
  1642. }
  1643. },
  1644. heatDomain: {
  1645. layerClass: function() { return 'heat-domain domain-' + this.constants.index; },
  1646. makeElements(data) {
  1647. let {index, colWidth, rowHeight, squareSize, xTranslate} = this.constants;
  1648. let monthNameHeight = -12;
  1649. let x = xTranslate, y = 0;
  1650. this.serializedSubDomains = [];
  1651. data.cols.map((week, weekNo) => {
  1652. if(weekNo === 1) {
  1653. this.labels.push(
  1654. makeText('domain-name', x, monthNameHeight, getMonthName(index, true).toUpperCase(),
  1655. {
  1656. fontSize: 9
  1657. }
  1658. )
  1659. );
  1660. }
  1661. week.map((day, i) => {
  1662. if(day.fill) {
  1663. let data = {
  1664. 'data-date': day.yyyyMmDd,
  1665. 'data-value': day.dataValue,
  1666. 'data-day': i
  1667. };
  1668. let square = heatSquare('day', x, y, squareSize, day.fill, data);
  1669. this.serializedSubDomains.push(square);
  1670. }
  1671. y += rowHeight;
  1672. });
  1673. y = 0;
  1674. x += colWidth;
  1675. });
  1676. return this.serializedSubDomains;
  1677. },
  1678. animateElements(newData) {
  1679. if(newData) return [];
  1680. }
  1681. },
  1682. barGraph: {
  1683. layerClass: function() { return 'dataset-units dataset-bars dataset-' + this.constants.index; },
  1684. makeElements(data) {
  1685. let c = this.constants;
  1686. this.unitType = 'bar';
  1687. this.units = data.yPositions.map((y, j) => {
  1688. return datasetBar(
  1689. data.xPositions[j],
  1690. y,
  1691. data.barWidth,
  1692. c.color,
  1693. data.labels[j],
  1694. j,
  1695. data.offsets[j],
  1696. {
  1697. zeroLine: data.zeroLine,
  1698. barsWidth: data.barsWidth,
  1699. minHeight: c.minHeight
  1700. }
  1701. );
  1702. });
  1703. return this.units;
  1704. },
  1705. animateElements(newData) {
  1706. let newXPos = newData.xPositions;
  1707. let newYPos = newData.yPositions;
  1708. let newOffsets = newData.offsets;
  1709. let newLabels = newData.labels;
  1710. let oldXPos = this.oldData.xPositions;
  1711. let oldYPos = this.oldData.yPositions;
  1712. let oldOffsets = this.oldData.offsets;
  1713. let oldLabels = this.oldData.labels;
  1714. [oldXPos, newXPos] = equilizeNoOfElements(oldXPos, newXPos);
  1715. [oldYPos, newYPos] = equilizeNoOfElements(oldYPos, newYPos);
  1716. [oldOffsets, newOffsets] = equilizeNoOfElements(oldOffsets, newOffsets);
  1717. [oldLabels, newLabels] = equilizeNoOfElements(oldLabels, newLabels);
  1718. this.render({
  1719. xPositions: oldXPos,
  1720. yPositions: oldYPos,
  1721. offsets: oldOffsets,
  1722. labels: newLabels,
  1723. zeroLine: this.oldData.zeroLine,
  1724. barsWidth: this.oldData.barsWidth,
  1725. barWidth: this.oldData.barWidth,
  1726. });
  1727. let animateElements = [];
  1728. this.store.map((bar, i) => {
  1729. animateElements = animateElements.concat(animateBar(
  1730. bar, newXPos[i], newYPos[i], newData.barWidth, newOffsets[i],
  1731. {zeroLine: newData.zeroLine}
  1732. ));
  1733. });
  1734. return animateElements;
  1735. }
  1736. },
  1737. lineGraph: {
  1738. layerClass: function() { return 'dataset-units dataset-line dataset-' + this.constants.index; },
  1739. makeElements(data) {
  1740. let c = this.constants;
  1741. this.unitType = 'dot';
  1742. this.paths = {};
  1743. if(!c.hideLine) {
  1744. this.paths = getPaths(
  1745. data.xPositions,
  1746. data.yPositions,
  1747. c.color,
  1748. {
  1749. heatline: c.heatline,
  1750. regionFill: c.regionFill
  1751. },
  1752. {
  1753. svgDefs: c.svgDefs,
  1754. zeroLine: data.zeroLine
  1755. }
  1756. );
  1757. }
  1758. this.units = [];
  1759. if(!c.hideDots) {
  1760. this.units = data.yPositions.map((y, j) => {
  1761. return datasetDot(
  1762. data.xPositions[j],
  1763. y,
  1764. data.radius,
  1765. c.color,
  1766. (c.valuesOverPoints ? data.values[j] : ''),
  1767. j
  1768. );
  1769. });
  1770. }
  1771. return Object.values(this.paths).concat(this.units);
  1772. },
  1773. animateElements(newData) {
  1774. let newXPos = newData.xPositions;
  1775. let newYPos = newData.yPositions;
  1776. let newValues = newData.values;
  1777. let oldXPos = this.oldData.xPositions;
  1778. let oldYPos = this.oldData.yPositions;
  1779. let oldValues = this.oldData.values;
  1780. [oldXPos, newXPos] = equilizeNoOfElements(oldXPos, newXPos);
  1781. [oldYPos, newYPos] = equilizeNoOfElements(oldYPos, newYPos);
  1782. [oldValues, newValues] = equilizeNoOfElements(oldValues, newValues);
  1783. this.render({
  1784. xPositions: oldXPos,
  1785. yPositions: oldYPos,
  1786. values: newValues,
  1787. zeroLine: this.oldData.zeroLine,
  1788. radius: this.oldData.radius,
  1789. });
  1790. let animateElements = [];
  1791. if(Object.keys(this.paths).length) {
  1792. animateElements = animateElements.concat(animatePath(
  1793. this.paths, newXPos, newYPos, newData.zeroLine));
  1794. }
  1795. if(this.units.length) {
  1796. this.units.map((dot, i) => {
  1797. animateElements = animateElements.concat(animateDot(
  1798. dot, newXPos[i], newYPos[i]));
  1799. });
  1800. }
  1801. return animateElements;
  1802. }
  1803. }
  1804. };
  1805. function getComponent(name, constants, getData) {
  1806. let keys = Object.keys(componentConfigs).filter(k => name.includes(k));
  1807. let config = componentConfigs[keys[0]];
  1808. Object.assign(config, {
  1809. constants: constants,
  1810. getData: getData
  1811. });
  1812. return new ChartComponent(config);
  1813. }
  1814. class PercentageChart extends AggregationChart {
  1815. constructor(parent, args) {
  1816. super(parent, args);
  1817. this.type = 'percentage';
  1818. this.barOptions = args.barOptions || {};
  1819. this.barOptions.height = this.barOptions.height
  1820. || PERCENTAGE_BAR_DEFAULT_HEIGHT;
  1821. this.barOptions.depth = this.barOptions.depth
  1822. || PERCENTAGE_BAR_DEFAULT_DEPTH;
  1823. this.setup();
  1824. }
  1825. setupComponents() {
  1826. let s = this.state;
  1827. let componentConfigs = [
  1828. [
  1829. 'percentageBars',
  1830. {
  1831. barHeight: this.barOptions.height,
  1832. barDepth: this.barOptions.depth,
  1833. },
  1834. function() {
  1835. return {
  1836. xPositions: s.xPositions,
  1837. widths: s.widths,
  1838. colors: this.colors
  1839. };
  1840. }.bind(this)
  1841. ]
  1842. ];
  1843. this.components = new Map(componentConfigs
  1844. .map(args => {
  1845. let component = getComponent(...args);
  1846. return [args[0], component];
  1847. }));
  1848. }
  1849. calc() {
  1850. super.calc();
  1851. let s = this.state;
  1852. s.xPositions = [];
  1853. s.widths = [];
  1854. let xPos = 0;
  1855. s.sliceTotals.map((value) => {
  1856. let width = this.width * value / s.grandTotal;
  1857. s.widths.push(width);
  1858. s.xPositions.push(xPos);
  1859. xPos += width;
  1860. });
  1861. }
  1862. makeDataByIndex() { }
  1863. bindTooltip() {
  1864. let s = this.state;
  1865. this.container.addEventListener('mousemove', (e) => {
  1866. let bars = this.components.get('percentageBars').store;
  1867. let bar = e.target;
  1868. if(bars.includes(bar)) {
  1869. let i = bars.indexOf(bar);
  1870. let gOff = getOffset(this.container), pOff = getOffset(bar);
  1871. let x = pOff.left - gOff.left + parseInt(bar.getAttribute('width'))/2;
  1872. let y = pOff.top - gOff.top;
  1873. let title = (this.formattedLabels && this.formattedLabels.length>0
  1874. ? this.formattedLabels[i] : this.state.labels[i]) + ': ';
  1875. let fraction = s.sliceTotals[i]/s.grandTotal;
  1876. this.tip.setValues(x, y, {name: title, value: (fraction*100).toFixed(1) + "%"});
  1877. this.tip.showTip();
  1878. }
  1879. });
  1880. }
  1881. }
  1882. class PieChart extends AggregationChart {
  1883. constructor(parent, args) {
  1884. super(parent, args);
  1885. this.type = 'pie';
  1886. this.initTimeout = 0;
  1887. this.init = 1;
  1888. this.setup();
  1889. }
  1890. configure(args) {
  1891. super.configure(args);
  1892. this.mouseMove = this.mouseMove.bind(this);
  1893. this.mouseLeave = this.mouseLeave.bind(this);
  1894. this.hoverRadio = args.hoverRadio || 0.1;
  1895. this.config.startAngle = args.startAngle || 0;
  1896. this.clockWise = args.clockWise || false;
  1897. }
  1898. calc() {
  1899. super.calc();
  1900. let s = this.state;
  1901. this.radius = (this.height > this.width ? this.center.x : this.center.y);
  1902. const { radius, clockWise } = this;
  1903. const prevSlicesProperties = s.slicesProperties || [];
  1904. s.sliceStrings = [];
  1905. s.slicesProperties = [];
  1906. let curAngle = 180 - this.config.startAngle;
  1907. s.sliceTotals.map((total, i) => {
  1908. const startAngle = curAngle;
  1909. const originDiffAngle = (total / s.grandTotal) * FULL_ANGLE;
  1910. const diffAngle = clockWise ? -originDiffAngle : originDiffAngle;
  1911. const endAngle = curAngle = curAngle + diffAngle;
  1912. const startPosition = getPositionByAngle(startAngle, radius);
  1913. const endPosition = getPositionByAngle(endAngle, radius);
  1914. const prevProperty = this.init && prevSlicesProperties[i];
  1915. let curStart,curEnd;
  1916. if(this.init) {
  1917. curStart = prevProperty ? prevProperty.startPosition : startPosition;
  1918. curEnd = prevProperty ? prevProperty.endPosition : startPosition;
  1919. } else {
  1920. curStart = startPosition;
  1921. curEnd = endPosition;
  1922. }
  1923. const curPath = makeArcPathStr(curStart, curEnd, this.center, this.radius, this.clockWise);
  1924. s.sliceStrings.push(curPath);
  1925. s.slicesProperties.push({
  1926. startPosition,
  1927. endPosition,
  1928. value: total,
  1929. total: s.grandTotal,
  1930. startAngle,
  1931. endAngle,
  1932. angle: diffAngle
  1933. });
  1934. });
  1935. this.init = 0;
  1936. }
  1937. setupComponents() {
  1938. let s = this.state;
  1939. let componentConfigs = [
  1940. [
  1941. 'pieSlices',
  1942. { },
  1943. function() {
  1944. return {
  1945. sliceStrings: s.sliceStrings,
  1946. colors: this.colors
  1947. };
  1948. }.bind(this)
  1949. ]
  1950. ];
  1951. this.components = new Map(componentConfigs
  1952. .map(args => {
  1953. let component = getComponent(...args);
  1954. return [args[0], component];
  1955. }));
  1956. }
  1957. calTranslateByAngle(property){
  1958. const{radius,hoverRadio} = this;
  1959. const position = getPositionByAngle(property.startAngle+(property.angle / 2),radius);
  1960. return `translate3d(${(position.x) * hoverRadio}px,${(position.y) * hoverRadio}px,0)`;
  1961. }
  1962. hoverSlice(path,i,flag,e){
  1963. if(!path) return;
  1964. const color = this.colors[i];
  1965. if(flag) {
  1966. transform(path, this.calTranslateByAngle(this.state.slicesProperties[i]));
  1967. path.style.fill = lightenDarkenColor(color, 50);
  1968. let g_off = getOffset(this.svg);
  1969. let x = e.pageX - g_off.left + 10;
  1970. let y = e.pageY - g_off.top - 10;
  1971. let title = (this.formatted_labels && this.formatted_labels.length > 0
  1972. ? this.formatted_labels[i] : this.state.labels[i]) + ': ';
  1973. let percent = (this.state.sliceTotals[i] * 100 / this.state.grandTotal).toFixed(1);
  1974. this.tip.setValues(x, y, {name: title, value: percent + "%"});
  1975. this.tip.showTip();
  1976. } else {
  1977. transform(path,'translate3d(0,0,0)');
  1978. this.tip.hideTip();
  1979. path.style.fill = color;
  1980. }
  1981. }
  1982. bindTooltip() {
  1983. this.container.addEventListener('mousemove', this.mouseMove);
  1984. this.container.addEventListener('mouseleave', this.mouseLeave);
  1985. }
  1986. mouseMove(e){
  1987. const target = e.target;
  1988. let slices = this.components.get('pieSlices').store;
  1989. let prevIndex = this.curActiveSliceIndex;
  1990. let prevAcitve = this.curActiveSlice;
  1991. if(slices.includes(target)) {
  1992. let i = slices.indexOf(target);
  1993. this.hoverSlice(prevAcitve, prevIndex,false);
  1994. this.curActiveSlice = target;
  1995. this.curActiveSliceIndex = i;
  1996. this.hoverSlice(target, i, true, e);
  1997. } else {
  1998. this.mouseLeave();
  1999. }
  2000. }
  2001. mouseLeave(){
  2002. this.hoverSlice(this.curActiveSlice,this.curActiveSliceIndex,false);
  2003. }
  2004. }
  2005. function normalize(x) {
  2006. // Calculates mantissa and exponent of a number
  2007. // Returns normalized number and exponent
  2008. // https://stackoverflow.com/q/9383593/6495043
  2009. if(x===0) {
  2010. return [0, 0];
  2011. }
  2012. if(isNaN(x)) {
  2013. return {mantissa: -6755399441055744, exponent: 972};
  2014. }
  2015. var sig = x > 0 ? 1 : -1;
  2016. if(!isFinite(x)) {
  2017. return {mantissa: sig * 4503599627370496, exponent: 972};
  2018. }
  2019. x = Math.abs(x);
  2020. var exp = Math.floor(Math.log10(x));
  2021. var man = x/Math.pow(10, exp);
  2022. return [sig * man, exp];
  2023. }
  2024. function getChartRangeIntervals(max, min=0) {
  2025. let upperBound = Math.ceil(max);
  2026. let lowerBound = Math.floor(min);
  2027. let range = upperBound - lowerBound;
  2028. let noOfParts = range;
  2029. let partSize = 1;
  2030. // To avoid too many partitions
  2031. if(range > 5) {
  2032. if(range % 2 !== 0) {
  2033. upperBound++;
  2034. // Recalc range
  2035. range = upperBound - lowerBound;
  2036. }
  2037. noOfParts = range/2;
  2038. partSize = 2;
  2039. }
  2040. // Special case: 1 and 2
  2041. if(range <= 2) {
  2042. noOfParts = 4;
  2043. partSize = range/noOfParts;
  2044. }
  2045. // Special case: 0
  2046. if(range === 0) {
  2047. noOfParts = 5;
  2048. partSize = 1;
  2049. }
  2050. let intervals = [];
  2051. for(var i = 0; i <= noOfParts; i++){
  2052. intervals.push(lowerBound + partSize * i);
  2053. }
  2054. return intervals;
  2055. }
  2056. function getChartIntervals(maxValue, minValue=0) {
  2057. let [normalMaxValue, exponent] = normalize(maxValue);
  2058. let normalMinValue = minValue ? minValue/Math.pow(10, exponent): 0;
  2059. // Allow only 7 significant digits
  2060. normalMaxValue = normalMaxValue.toFixed(6);
  2061. let intervals = getChartRangeIntervals(normalMaxValue, normalMinValue);
  2062. intervals = intervals.map(value => value * Math.pow(10, exponent));
  2063. return intervals;
  2064. }
  2065. function calcChartIntervals(values, withMinimum=false) {
  2066. //*** Where the magic happens ***
  2067. // Calculates best-fit y intervals from given values
  2068. // and returns the interval array
  2069. let maxValue = Math.max(...values);
  2070. let minValue = Math.min(...values);
  2071. // Exponent to be used for pretty print
  2072. let exponent = 0, intervals = []; // eslint-disable-line no-unused-vars
  2073. function getPositiveFirstIntervals(maxValue, absMinValue) {
  2074. let intervals = getChartIntervals(maxValue);
  2075. let intervalSize = intervals[1] - intervals[0];
  2076. // Then unshift the negative values
  2077. let value = 0;
  2078. for(var i = 1; value < absMinValue; i++) {
  2079. value += intervalSize;
  2080. intervals.unshift((-1) * value);
  2081. }
  2082. return intervals;
  2083. }
  2084. // CASE I: Both non-negative
  2085. if(maxValue >= 0 && minValue >= 0) {
  2086. exponent = normalize(maxValue)[1];
  2087. if(!withMinimum) {
  2088. intervals = getChartIntervals(maxValue);
  2089. } else {
  2090. intervals = getChartIntervals(maxValue, minValue);
  2091. }
  2092. }
  2093. // CASE II: Only minValue negative
  2094. else if(maxValue > 0 && minValue < 0) {
  2095. // `withMinimum` irrelevant in this case,
  2096. // We'll be handling both sides of zero separately
  2097. // (both starting from zero)
  2098. // Because ceil() and floor() behave differently
  2099. // in those two regions
  2100. let absMinValue = Math.abs(minValue);
  2101. if(maxValue >= absMinValue) {
  2102. exponent = normalize(maxValue)[1];
  2103. intervals = getPositiveFirstIntervals(maxValue, absMinValue);
  2104. } else {
  2105. // Mirror: maxValue => absMinValue, then change sign
  2106. exponent = normalize(absMinValue)[1];
  2107. let posIntervals = getPositiveFirstIntervals(absMinValue, maxValue);
  2108. intervals = posIntervals.map(d => d * (-1));
  2109. }
  2110. }
  2111. // CASE III: Both non-positive
  2112. else if(maxValue <= 0 && minValue <= 0) {
  2113. // Mirrored Case I:
  2114. // Work with positives, then reverse the sign and array
  2115. let pseudoMaxValue = Math.abs(minValue);
  2116. let pseudoMinValue = Math.abs(maxValue);
  2117. exponent = normalize(pseudoMaxValue)[1];
  2118. if(!withMinimum) {
  2119. intervals = getChartIntervals(pseudoMaxValue);
  2120. } else {
  2121. intervals = getChartIntervals(pseudoMaxValue, pseudoMinValue);
  2122. }
  2123. intervals = intervals.reverse().map(d => d * (-1));
  2124. }
  2125. return intervals;
  2126. }
  2127. function getZeroIndex(yPts) {
  2128. let zeroIndex;
  2129. let interval = getIntervalSize(yPts);
  2130. if(yPts.indexOf(0) >= 0) {
  2131. // the range has a given zero
  2132. // zero-line on the chart
  2133. zeroIndex = yPts.indexOf(0);
  2134. } else if(yPts[0] > 0) {
  2135. // Minimum value is positive
  2136. // zero-line is off the chart: below
  2137. let min = yPts[0];
  2138. zeroIndex = (-1) * min / interval;
  2139. } else {
  2140. // Maximum value is negative
  2141. // zero-line is off the chart: above
  2142. let max = yPts[yPts.length - 1];
  2143. zeroIndex = (-1) * max / interval + (yPts.length - 1);
  2144. }
  2145. return zeroIndex;
  2146. }
  2147. function getIntervalSize(orderedArray) {
  2148. return orderedArray[1] - orderedArray[0];
  2149. }
  2150. function getValueRange(orderedArray) {
  2151. return orderedArray[orderedArray.length-1] - orderedArray[0];
  2152. }
  2153. function scale(val, yAxis) {
  2154. return floatTwo(yAxis.zeroLine - val * yAxis.scaleMultiplier);
  2155. }
  2156. function getClosestInArray(goal, arr, index = false) {
  2157. let closest = arr.reduce(function(prev, curr) {
  2158. return (Math.abs(curr - goal) < Math.abs(prev - goal) ? curr : prev);
  2159. });
  2160. return index ? arr.indexOf(closest) : closest;
  2161. }
  2162. function calcDistribution(values, distributionSize) {
  2163. // Assume non-negative values,
  2164. // implying distribution minimum at zero
  2165. let dataMaxValue = Math.max(...values);
  2166. let distributionStep = 1 / (distributionSize - 1);
  2167. let distribution = [];
  2168. for(var i = 0; i < distributionSize; i++) {
  2169. let checkpoint = dataMaxValue * (distributionStep * i);
  2170. distribution.push(checkpoint);
  2171. }
  2172. return distribution;
  2173. }
  2174. function getMaxCheckpoint(value, distribution) {
  2175. return distribution.filter(d => d < value).length;
  2176. }
  2177. const COL_WIDTH = HEATMAP_SQUARE_SIZE + HEATMAP_GUTTER_SIZE;
  2178. const ROW_HEIGHT = COL_WIDTH;
  2179. // const DAY_INCR = 1;
  2180. class Heatmap extends BaseChart {
  2181. constructor(parent, options) {
  2182. super(parent, options);
  2183. this.type = 'heatmap';
  2184. this.countLabel = options.countLabel || '';
  2185. let validStarts = ['Sunday', 'Monday'];
  2186. let startSubDomain = validStarts.includes(options.startSubDomain)
  2187. ? options.startSubDomain : 'Sunday';
  2188. this.startSubDomainIndex = validStarts.indexOf(startSubDomain);
  2189. this.setup();
  2190. }
  2191. setMeasures(options) {
  2192. let m = this.measures;
  2193. this.discreteDomains = options.discreteDomains === 0 ? 0 : 1;
  2194. m.paddings.top = ROW_HEIGHT * 3;
  2195. m.paddings.bottom = 0;
  2196. m.legendHeight = ROW_HEIGHT * 2;
  2197. m.baseHeight = ROW_HEIGHT * NO_OF_DAYS_IN_WEEK
  2198. + getExtraHeight(m);
  2199. let d = this.data;
  2200. let spacing = this.discreteDomains ? NO_OF_YEAR_MONTHS : 0;
  2201. this.independentWidth = (getWeeksBetween(d.start, d.end)
  2202. + spacing) * COL_WIDTH + m.margins.right + m.margins.left;
  2203. }
  2204. updateWidth() {
  2205. let spacing = this.discreteDomains ? NO_OF_YEAR_MONTHS : 0;
  2206. this.baseWidth = (this.state.noOfWeeks + spacing) * COL_WIDTH
  2207. + getExtraWidth(this.measures);
  2208. }
  2209. prepareData(data=this.data) {
  2210. if(data.start && data.end && data.start > data.end) {
  2211. throw new Error('Start date cannot be greater than end date.');
  2212. }
  2213. if(!data.start) {
  2214. data.start = new Date();
  2215. data.start.setFullYear( data.start.getFullYear() - 1 );
  2216. }
  2217. if(!data.end) { data.end = new Date(); }
  2218. data.dataPoints = data.dataPoints || {};
  2219. if(parseInt(Object.keys(data.dataPoints)[0]) > 100000) {
  2220. let points = {};
  2221. Object.keys(data.dataPoints).forEach(timestampSec$$1 => {
  2222. let date = new Date(timestampSec$$1 * NO_OF_MILLIS);
  2223. points[getYyyyMmDd(date)] = data.dataPoints[timestampSec$$1];
  2224. });
  2225. data.dataPoints = points;
  2226. }
  2227. return data;
  2228. }
  2229. calc() {
  2230. let s = this.state;
  2231. s.start = clone(this.data.start);
  2232. s.end = clone(this.data.end);
  2233. s.firstWeekStart = clone(s.start);
  2234. s.noOfWeeks = getWeeksBetween(s.start, s.end);
  2235. s.distribution = calcDistribution(
  2236. Object.values(this.data.dataPoints), HEATMAP_DISTRIBUTION_SIZE);
  2237. s.domainConfigs = this.getDomains();
  2238. }
  2239. setupComponents() {
  2240. let s = this.state;
  2241. let lessCol = this.discreteDomains ? 0 : 1;
  2242. let componentConfigs = s.domainConfigs.map((config, i) => [
  2243. 'heatDomain',
  2244. {
  2245. index: config.index,
  2246. colWidth: COL_WIDTH,
  2247. rowHeight: ROW_HEIGHT,
  2248. squareSize: HEATMAP_SQUARE_SIZE,
  2249. xTranslate: s.domainConfigs
  2250. .filter((config, j) => j < i)
  2251. .map(config => config.cols.length - lessCol)
  2252. .reduce((a, b) => a + b, 0)
  2253. * COL_WIDTH
  2254. },
  2255. function() {
  2256. return s.domainConfigs[i];
  2257. }.bind(this)
  2258. ]);
  2259. this.components = new Map(componentConfigs
  2260. .map((args, i) => {
  2261. let component = getComponent(...args);
  2262. return [args[0] + '-' + i, component];
  2263. })
  2264. );
  2265. let y = 0;
  2266. DAY_NAMES_SHORT.forEach((dayName, i) => {
  2267. if([1, 3, 5].includes(i)) {
  2268. let dayText = makeText('subdomain-name', -COL_WIDTH/2, y, dayName,
  2269. {
  2270. fontSize: HEATMAP_SQUARE_SIZE,
  2271. dy: 8,
  2272. textAnchor: 'end'
  2273. }
  2274. );
  2275. this.drawArea.appendChild(dayText);
  2276. }
  2277. y += ROW_HEIGHT;
  2278. });
  2279. }
  2280. update(data) {
  2281. if(!data) {
  2282. console.error('No data to update.');
  2283. }
  2284. this.data = this.prepareData(data);
  2285. this.draw();
  2286. this.bindTooltip();
  2287. }
  2288. bindTooltip() {
  2289. this.container.addEventListener('mousemove', (e) => {
  2290. this.components.forEach(comp => {
  2291. let daySquares = comp.store;
  2292. let daySquare = e.target;
  2293. if(daySquares.includes(daySquare)) {
  2294. let count = daySquare.getAttribute('data-value');
  2295. let dateParts = daySquare.getAttribute('data-date').split('-');
  2296. let month = getMonthName(parseInt(dateParts[1])-1, true);
  2297. let gOff = this.container.getBoundingClientRect(), pOff = daySquare.getBoundingClientRect();
  2298. let width = parseInt(e.target.getAttribute('width'));
  2299. let x = pOff.left - gOff.left + width/2;
  2300. let y = pOff.top - gOff.top;
  2301. let value = count + ' ' + this.countLabel;
  2302. let name = ' on ' + month + ' ' + dateParts[0] + ', ' + dateParts[2];
  2303. this.tip.setValues(x, y, {name: name, value: value, valueFirst: 1}, []);
  2304. this.tip.showTip();
  2305. }
  2306. });
  2307. });
  2308. }
  2309. renderLegend() {
  2310. this.legendArea.textContent = '';
  2311. let x = 0;
  2312. let y = ROW_HEIGHT;
  2313. let lessText = makeText('subdomain-name', x, y, 'Less',
  2314. {
  2315. fontSize: HEATMAP_SQUARE_SIZE + 1,
  2316. dy: 9
  2317. }
  2318. );
  2319. x = (COL_WIDTH * 2) + COL_WIDTH/2;
  2320. this.legendArea.appendChild(lessText);
  2321. this.colors.slice(0, HEATMAP_DISTRIBUTION_SIZE).map((color, i) => {
  2322. const square = heatSquare('heatmap-legend-unit', x + (COL_WIDTH + 3) * i,
  2323. y, HEATMAP_SQUARE_SIZE, color);
  2324. this.legendArea.appendChild(square);
  2325. });
  2326. let moreTextX = x + HEATMAP_DISTRIBUTION_SIZE * (COL_WIDTH + 3) + COL_WIDTH/4;
  2327. let moreText = makeText('subdomain-name', moreTextX, y, 'More',
  2328. {
  2329. fontSize: HEATMAP_SQUARE_SIZE + 1,
  2330. dy: 9
  2331. }
  2332. );
  2333. this.legendArea.appendChild(moreText);
  2334. }
  2335. getDomains() {
  2336. let s = this.state;
  2337. const [startMonth, startYear] = [s.start.getMonth(), s.start.getFullYear()];
  2338. const [endMonth, endYear] = [s.end.getMonth(), s.end.getFullYear()];
  2339. const noOfMonths = (endMonth - startMonth + 1) + (endYear - startYear) * 12;
  2340. let domainConfigs = [];
  2341. let startOfMonth = clone(s.start);
  2342. for(var i = 0; i < noOfMonths; i++) {
  2343. let endDate = s.end;
  2344. if(!areInSameMonth(startOfMonth, s.end)) {
  2345. let [month, year] = [startOfMonth.getMonth(), startOfMonth.getFullYear()];
  2346. endDate = getLastDateInMonth(month, year);
  2347. }
  2348. domainConfigs.push(this.getDomainConfig(startOfMonth, endDate));
  2349. addDays(endDate, 1);
  2350. startOfMonth = endDate;
  2351. }
  2352. return domainConfigs;
  2353. }
  2354. getDomainConfig(startDate, endDate='') {
  2355. let [month, year] = [startDate.getMonth(), startDate.getFullYear()];
  2356. let startOfWeek = setDayToSunday(startDate); // TODO: Monday as well
  2357. endDate = clone(endDate) || getLastDateInMonth(month, year);
  2358. let domainConfig = {
  2359. index: month,
  2360. cols: []
  2361. };
  2362. addDays(endDate, 1);
  2363. let noOfMonthWeeks = getWeeksBetween(startOfWeek, endDate);
  2364. let cols = [], col;
  2365. for(var i = 0; i < noOfMonthWeeks; i++) {
  2366. col = this.getCol(startOfWeek, month);
  2367. cols.push(col);
  2368. startOfWeek = new Date(col[NO_OF_DAYS_IN_WEEK - 1].yyyyMmDd);
  2369. addDays(startOfWeek, 1);
  2370. }
  2371. if(col[NO_OF_DAYS_IN_WEEK - 1].dataValue !== undefined) {
  2372. addDays(startOfWeek, 1);
  2373. cols.push(this.getCol(startOfWeek, month, true));
  2374. }
  2375. domainConfig.cols = cols;
  2376. return domainConfig;
  2377. }
  2378. getCol(startDate, month, empty = false) {
  2379. let s = this.state;
  2380. // startDate is the start of week
  2381. let currentDate = clone(startDate);
  2382. let col = [];
  2383. for(var i = 0; i < NO_OF_DAYS_IN_WEEK; i++, addDays(currentDate, 1)) {
  2384. let config = {};
  2385. // Non-generic adjustment for entire heatmap, needs state
  2386. let currentDateWithinData = currentDate >= s.start && currentDate <= s.end;
  2387. if(empty || currentDate.getMonth() !== month || !currentDateWithinData) {
  2388. config.yyyyMmDd = getYyyyMmDd(currentDate);
  2389. } else {
  2390. config = this.getSubDomainConfig(currentDate);
  2391. }
  2392. col.push(config);
  2393. }
  2394. return col;
  2395. }
  2396. getSubDomainConfig(date) {
  2397. let yyyyMmDd = getYyyyMmDd(date);
  2398. let dataValue = this.data.dataPoints[yyyyMmDd];
  2399. let config = {
  2400. yyyyMmDd: yyyyMmDd,
  2401. dataValue: dataValue || 0,
  2402. fill: this.colors[getMaxCheckpoint(dataValue, this.state.distribution)]
  2403. };
  2404. return config;
  2405. }
  2406. }
  2407. function dataPrep(data, type) {
  2408. data.labels = data.labels || [];
  2409. let datasetLength = data.labels.length;
  2410. // Datasets
  2411. let datasets = data.datasets;
  2412. let zeroArray = new Array(datasetLength).fill(0);
  2413. if(!datasets) {
  2414. // default
  2415. datasets = [{
  2416. values: zeroArray
  2417. }];
  2418. }
  2419. datasets.map(d=> {
  2420. // Set values
  2421. if(!d.values) {
  2422. d.values = zeroArray;
  2423. } else {
  2424. // Check for non values
  2425. let vals = d.values;
  2426. vals = vals.map(val => (!isNaN(val) ? val : 0));
  2427. // Trim or extend
  2428. if(vals.length > datasetLength) {
  2429. vals = vals.slice(0, datasetLength);
  2430. } else {
  2431. vals = fillArray(vals, datasetLength - vals.length, 0);
  2432. }
  2433. }
  2434. // Set labels
  2435. //
  2436. // Set type
  2437. if(!d.chartType ) {
  2438. if(!AXIS_DATASET_CHART_TYPES.includes(type)) type === DEFAULT_AXIS_CHART_TYPE;
  2439. d.chartType = type;
  2440. }
  2441. });
  2442. // Markers
  2443. // Regions
  2444. // data.yRegions = data.yRegions || [];
  2445. if(data.yRegions) {
  2446. data.yRegions.map(d => {
  2447. if(d.end < d.start) {
  2448. [d.start, d.end] = [d.end, d.start];
  2449. }
  2450. });
  2451. }
  2452. return data;
  2453. }
  2454. function zeroDataPrep(realData) {
  2455. let datasetLength = realData.labels.length;
  2456. let zeroArray = new Array(datasetLength).fill(0);
  2457. let zeroData = {
  2458. labels: realData.labels.slice(0, -1),
  2459. datasets: realData.datasets.map(d => {
  2460. return {
  2461. name: '',
  2462. values: zeroArray.slice(0, -1),
  2463. chartType: d.chartType
  2464. };
  2465. }),
  2466. };
  2467. if(realData.yMarkers) {
  2468. zeroData.yMarkers = [
  2469. {
  2470. value: 0,
  2471. label: ''
  2472. }
  2473. ];
  2474. }
  2475. if(realData.yRegions) {
  2476. zeroData.yRegions = [
  2477. {
  2478. start: 0,
  2479. end: 0,
  2480. label: ''
  2481. }
  2482. ];
  2483. }
  2484. return zeroData;
  2485. }
  2486. function getShortenedLabels(chartWidth, labels=[], isSeries=true) {
  2487. let allowedSpace = chartWidth / labels.length;
  2488. let allowedLetters = allowedSpace / DEFAULT_CHAR_WIDTH;
  2489. let calcLabels = labels.map((label, i) => {
  2490. label += "";
  2491. if(label.length > allowedLetters) {
  2492. if(!isSeries) {
  2493. if(allowedLetters-3 > 0) {
  2494. label = label.slice(0, allowedLetters-3) + " ...";
  2495. } else {
  2496. label = label.slice(0, allowedLetters) + '..';
  2497. }
  2498. } else {
  2499. let multiple = Math.ceil(label.length/allowedLetters);
  2500. if(i % multiple !== 0) {
  2501. label = "";
  2502. }
  2503. }
  2504. }
  2505. return label;
  2506. });
  2507. return calcLabels;
  2508. }
  2509. class AxisChart extends BaseChart {
  2510. constructor(parent, args) {
  2511. super(parent, args);
  2512. this.barOptions = args.barOptions || {};
  2513. this.lineOptions = args.lineOptions || {};
  2514. this.type = args.type || 'line';
  2515. this.init = 1;
  2516. this.setup();
  2517. }
  2518. setMeasures(options) {
  2519. if(this.data.datasets.length <= 1) {
  2520. this.config.showLegend = 0;
  2521. this.measures.paddings.bottom = 30;
  2522. }
  2523. }
  2524. configure(options) {
  2525. super.configure(options);
  2526. options.axisOptions = options.axisOptions || {};
  2527. options.tooltipOptions = options.tooltipOptions || {};
  2528. this.config.xAxisMode = options.axisOptions.xAxisMode || 'span';
  2529. this.config.yAxisMode = options.axisOptions.yAxisMode || 'span';
  2530. this.config.xIsSeries = options.axisOptions.xIsSeries || 0;
  2531. this.config.formatTooltipX = options.tooltipOptions.formatTooltipX;
  2532. this.config.formatTooltipY = options.tooltipOptions.formatTooltipY;
  2533. this.config.valuesOverPoints = options.valuesOverPoints;
  2534. }
  2535. prepareData(data=this.data) {
  2536. return dataPrep(data, this.type);
  2537. }
  2538. prepareFirstData(data=this.data) {
  2539. return zeroDataPrep(data);
  2540. }
  2541. calc(onlyWidthChange = false) {
  2542. this.calcXPositions();
  2543. if(onlyWidthChange) return;
  2544. this.calcYAxisParameters(this.getAllYValues(), this.type === 'line');
  2545. this.makeDataByIndex();
  2546. }
  2547. calcXPositions() {
  2548. let s = this.state;
  2549. let labels = this.data.labels;
  2550. s.datasetLength = labels.length;
  2551. s.unitWidth = this.width/(s.datasetLength);
  2552. // Default, as per bar, and mixed. Only line will be a special case
  2553. s.xOffset = s.unitWidth/2;
  2554. // // For a pure Line Chart
  2555. // s.unitWidth = this.width/(s.datasetLength - 1);
  2556. // s.xOffset = 0;
  2557. s.xAxis = {
  2558. labels: labels,
  2559. positions: labels.map((d, i) =>
  2560. floatTwo(s.xOffset + i * s.unitWidth)
  2561. )
  2562. };
  2563. }
  2564. calcYAxisParameters(dataValues, withMinimum = 'false') {
  2565. const yPts = calcChartIntervals(dataValues, withMinimum);
  2566. const scaleMultiplier = this.height / getValueRange(yPts);
  2567. const intervalHeight = getIntervalSize(yPts) * scaleMultiplier;
  2568. const zeroLine = this.height - (getZeroIndex(yPts) * intervalHeight);
  2569. this.state.yAxis = {
  2570. labels: yPts,
  2571. positions: yPts.map(d => zeroLine - d * scaleMultiplier),
  2572. scaleMultiplier: scaleMultiplier,
  2573. zeroLine: zeroLine,
  2574. };
  2575. // Dependent if above changes
  2576. this.calcDatasetPoints();
  2577. this.calcYExtremes();
  2578. this.calcYRegions();
  2579. }
  2580. calcDatasetPoints() {
  2581. let s = this.state;
  2582. let scaleAll = values => values.map(val => scale(val, s.yAxis));
  2583. s.datasets = this.data.datasets.map((d, i) => {
  2584. let values = d.values;
  2585. let cumulativeYs = d.cumulativeYs || [];
  2586. return {
  2587. name: d.name,
  2588. index: i,
  2589. chartType: d.chartType,
  2590. values: values,
  2591. yPositions: scaleAll(values),
  2592. cumulativeYs: cumulativeYs,
  2593. cumulativeYPos: scaleAll(cumulativeYs),
  2594. };
  2595. });
  2596. }
  2597. calcYExtremes() {
  2598. let s = this.state;
  2599. if(this.barOptions.stacked) {
  2600. s.yExtremes = s.datasets[s.datasets.length - 1].cumulativeYPos;
  2601. return;
  2602. }
  2603. s.yExtremes = new Array(s.datasetLength).fill(9999);
  2604. s.datasets.map(d => {
  2605. d.yPositions.map((pos, j) => {
  2606. if(pos < s.yExtremes[j]) {
  2607. s.yExtremes[j] = pos;
  2608. }
  2609. });
  2610. });
  2611. }
  2612. calcYRegions() {
  2613. let s = this.state;
  2614. if(this.data.yMarkers) {
  2615. this.state.yMarkers = this.data.yMarkers.map(d => {
  2616. d.position = scale(d.value, s.yAxis);
  2617. // if(!d.label.includes(':')) {
  2618. // d.label += ': ' + d.value;
  2619. // }
  2620. return d;
  2621. });
  2622. }
  2623. if(this.data.yRegions) {
  2624. this.state.yRegions = this.data.yRegions.map(d => {
  2625. d.startPos = scale(d.start, s.yAxis);
  2626. d.endPos = scale(d.end, s.yAxis);
  2627. return d;
  2628. });
  2629. }
  2630. }
  2631. getAllYValues() {
  2632. let key = 'values';
  2633. if(this.barOptions.stacked) {
  2634. key = 'cumulativeYs';
  2635. let cumulative = new Array(this.state.datasetLength).fill(0);
  2636. this.data.datasets.map((d, i) => {
  2637. let values = this.data.datasets[i].values;
  2638. d[key] = cumulative = cumulative.map((c, i) => c + values[i]);
  2639. });
  2640. }
  2641. let allValueLists = this.data.datasets.map(d => d[key]);
  2642. if(this.data.yMarkers) {
  2643. allValueLists.push(this.data.yMarkers.map(d => d.value));
  2644. }
  2645. if(this.data.yRegions) {
  2646. this.data.yRegions.map(d => {
  2647. allValueLists.push([d.end, d.start]);
  2648. });
  2649. }
  2650. return [].concat(...allValueLists);
  2651. }
  2652. setupComponents() {
  2653. let componentConfigs = [
  2654. [
  2655. 'yAxis',
  2656. {
  2657. mode: this.config.yAxisMode,
  2658. width: this.width,
  2659. // pos: 'right'
  2660. },
  2661. function() {
  2662. return this.state.yAxis;
  2663. }.bind(this)
  2664. ],
  2665. [
  2666. 'xAxis',
  2667. {
  2668. mode: this.config.xAxisMode,
  2669. height: this.height,
  2670. // pos: 'right'
  2671. },
  2672. function() {
  2673. let s = this.state;
  2674. s.xAxis.calcLabels = getShortenedLabels(this.width,
  2675. s.xAxis.labels, this.config.xIsSeries);
  2676. return s.xAxis;
  2677. }.bind(this)
  2678. ],
  2679. [
  2680. 'yRegions',
  2681. {
  2682. width: this.width,
  2683. pos: 'right'
  2684. },
  2685. function() {
  2686. return this.state.yRegions;
  2687. }.bind(this)
  2688. ],
  2689. ];
  2690. let barDatasets = this.state.datasets.filter(d => d.chartType === 'bar');
  2691. let lineDatasets = this.state.datasets.filter(d => d.chartType === 'line');
  2692. let barsConfigs = barDatasets.map(d => {
  2693. let index = d.index;
  2694. return [
  2695. 'barGraph' + '-' + d.index,
  2696. {
  2697. index: index,
  2698. color: this.colors[index],
  2699. stacked: this.barOptions.stacked,
  2700. // same for all datasets
  2701. valuesOverPoints: this.config.valuesOverPoints,
  2702. minHeight: this.height * MIN_BAR_PERCENT_HEIGHT,
  2703. },
  2704. function() {
  2705. let s = this.state;
  2706. let d = s.datasets[index];
  2707. let stacked = this.barOptions.stacked;
  2708. let spaceRatio = this.barOptions.spaceRatio || BAR_CHART_SPACE_RATIO;
  2709. let barsWidth = s.unitWidth * (1 - spaceRatio);
  2710. let barWidth = barsWidth/(stacked ? 1 : barDatasets.length);
  2711. let xPositions = s.xAxis.positions.map(x => x - barsWidth/2);
  2712. if(!stacked) {
  2713. xPositions = xPositions.map(p => p + barWidth * index);
  2714. }
  2715. let labels = new Array(s.datasetLength).fill('');
  2716. if(this.config.valuesOverPoints) {
  2717. if(stacked && d.index === s.datasets.length - 1) {
  2718. labels = d.cumulativeYs;
  2719. } else {
  2720. labels = d.values;
  2721. }
  2722. }
  2723. let offsets = new Array(s.datasetLength).fill(0);
  2724. if(stacked) {
  2725. offsets = d.yPositions.map((y, j) => y - d.cumulativeYPos[j]);
  2726. }
  2727. return {
  2728. xPositions: xPositions,
  2729. yPositions: d.yPositions,
  2730. offsets: offsets,
  2731. // values: d.values,
  2732. labels: labels,
  2733. zeroLine: s.yAxis.zeroLine,
  2734. barsWidth: barsWidth,
  2735. barWidth: barWidth,
  2736. };
  2737. }.bind(this)
  2738. ];
  2739. });
  2740. let lineConfigs = lineDatasets.map(d => {
  2741. let index = d.index;
  2742. return [
  2743. 'lineGraph' + '-' + d.index,
  2744. {
  2745. index: index,
  2746. color: this.colors[index],
  2747. svgDefs: this.svgDefs,
  2748. heatline: this.lineOptions.heatline,
  2749. regionFill: this.lineOptions.regionFill,
  2750. hideDots: this.lineOptions.hideDots,
  2751. hideLine: this.lineOptions.hideLine,
  2752. // same for all datasets
  2753. valuesOverPoints: this.config.valuesOverPoints,
  2754. },
  2755. function() {
  2756. let s = this.state;
  2757. let d = s.datasets[index];
  2758. return {
  2759. xPositions: s.xAxis.positions,
  2760. yPositions: d.yPositions,
  2761. values: d.values,
  2762. zeroLine: s.yAxis.zeroLine,
  2763. radius: this.lineOptions.dotSize || LINE_CHART_DOT_SIZE,
  2764. };
  2765. }.bind(this)
  2766. ];
  2767. });
  2768. let markerConfigs = [
  2769. [
  2770. 'yMarkers',
  2771. {
  2772. width: this.width,
  2773. pos: 'right'
  2774. },
  2775. function() {
  2776. return this.state.yMarkers;
  2777. }.bind(this)
  2778. ]
  2779. ];
  2780. componentConfigs = componentConfigs.concat(barsConfigs, lineConfigs, markerConfigs);
  2781. let optionals = ['yMarkers', 'yRegions'];
  2782. this.dataUnitComponents = [];
  2783. this.components = new Map(componentConfigs
  2784. .filter(args => !optionals.includes(args[0]) || this.state[args[0]])
  2785. .map(args => {
  2786. let component = getComponent(...args);
  2787. if(args[0].includes('lineGraph') || args[0].includes('barGraph')) {
  2788. this.dataUnitComponents.push(component);
  2789. }
  2790. return [args[0], component];
  2791. }));
  2792. }
  2793. makeDataByIndex() {
  2794. this.dataByIndex = {};
  2795. let s = this.state;
  2796. // let formatY = this.config.formatTooltipY;
  2797. let formatX = this.config.formatTooltipX;
  2798. let titles = s.xAxis.labels;
  2799. if(formatX && formatX(titles[0])) {
  2800. titles = titles.map(d=>formatX(d));
  2801. }
  2802. // formatY = formatY && formatY(s.yAxis.labels[0]) ? formatY : 0;
  2803. // yVal = formatY ? formatY(set.values[i]) : set.values[i]
  2804. }
  2805. bindTooltip() {
  2806. // NOTE: could be in tooltip itself, as it is a given functionality for its parent
  2807. this.container.addEventListener('mousemove', (e) => {
  2808. let m = this.measures;
  2809. let o = getOffset(this.container);
  2810. let relX = e.pageX - o.left - m.margins.left - m.paddings.left;
  2811. let relY = e.pageY - o.top;
  2812. if(relY < this.height + m.titleHeight + m.margins.top + m.paddings.top
  2813. && relY > m.titleHeight + m.margins.top + m.paddings.top) {
  2814. this.mapTooltipXPosition(relX);
  2815. } else {
  2816. this.tip.hideTip();
  2817. }
  2818. });
  2819. }
  2820. mapTooltipXPosition(relX) {
  2821. let s = this.state;
  2822. if(!s.yExtremes) return;
  2823. let index = getClosestInArray(relX, s.xAxis.positions, true);
  2824. console.log(relX, s.xAxis.positions[index], s.xAxis.positions, this.tip.offset.x);
  2825. this.tip.setValues(
  2826. s.xAxis.positions[index] + this.tip.offset.x,
  2827. s.yExtremes[index] + this.tip.offset.y,
  2828. {name: s.xAxis.labels[index], value: ''},
  2829. this.data.datasets.map((set, i) => {
  2830. return {
  2831. title: set.name,
  2832. value: set.values[index],
  2833. color: this.colors[i],
  2834. };
  2835. }),
  2836. index
  2837. );
  2838. this.tip.showTip();
  2839. }
  2840. renderLegend() {
  2841. let s = this.data;
  2842. if(s.datasets.length > 1) {
  2843. this.legendArea.textContent = '';
  2844. s.datasets.map((d, i) => {
  2845. let barWidth = AXIS_LEGEND_BAR_SIZE;
  2846. // let rightEndPoint = this.baseWidth - this.measures.margins.left - this.measures.margins.right;
  2847. // let multiplier = s.datasets.length - i;
  2848. let rect = legendBar(
  2849. // rightEndPoint - multiplier * barWidth, // To right align
  2850. barWidth * i,
  2851. '0',
  2852. barWidth,
  2853. this.colors[i],
  2854. d.name);
  2855. this.legendArea.appendChild(rect);
  2856. });
  2857. }
  2858. }
  2859. // Overlay
  2860. makeOverlay() {
  2861. if(this.init) {
  2862. this.init = 0;
  2863. return;
  2864. }
  2865. if(this.overlayGuides) {
  2866. this.overlayGuides.forEach(g => {
  2867. let o = g.overlay;
  2868. o.parentNode.removeChild(o);
  2869. });
  2870. }
  2871. this.overlayGuides = this.dataUnitComponents.map(c => {
  2872. return {
  2873. type: c.unitType,
  2874. overlay: undefined,
  2875. units: c.units,
  2876. };
  2877. });
  2878. if(this.state.currentIndex === undefined) {
  2879. this.state.currentIndex = this.state.datasetLength - 1;
  2880. }
  2881. // Render overlays
  2882. this.overlayGuides.map(d => {
  2883. let currentUnit = d.units[this.state.currentIndex];
  2884. d.overlay = makeOverlay[d.type](currentUnit);
  2885. this.drawArea.appendChild(d.overlay);
  2886. });
  2887. }
  2888. updateOverlayGuides() {
  2889. if(this.overlayGuides) {
  2890. this.overlayGuides.forEach(g => {
  2891. let o = g.overlay;
  2892. o.parentNode.removeChild(o);
  2893. });
  2894. }
  2895. }
  2896. bindOverlay() {
  2897. this.parent.addEventListener('data-select', () => {
  2898. this.updateOverlay();
  2899. });
  2900. }
  2901. bindUnits() {
  2902. this.dataUnitComponents.map(c => {
  2903. c.units.map(unit => {
  2904. unit.addEventListener('click', () => {
  2905. let index = unit.getAttribute('data-point-index');
  2906. this.setCurrentDataPoint(index);
  2907. });
  2908. });
  2909. });
  2910. // Note: Doesn't work as tooltip is absolutely positioned
  2911. this.tip.container.addEventListener('click', () => {
  2912. let index = this.tip.container.getAttribute('data-point-index');
  2913. this.setCurrentDataPoint(index);
  2914. });
  2915. }
  2916. updateOverlay() {
  2917. this.overlayGuides.map(d => {
  2918. let currentUnit = d.units[this.state.currentIndex];
  2919. updateOverlay[d.type](currentUnit, d.overlay);
  2920. });
  2921. }
  2922. onLeftArrow() {
  2923. this.setCurrentDataPoint(this.state.currentIndex - 1);
  2924. }
  2925. onRightArrow() {
  2926. this.setCurrentDataPoint(this.state.currentIndex + 1);
  2927. }
  2928. getDataPoint(index=this.state.currentIndex) {
  2929. let s = this.state;
  2930. let data_point = {
  2931. index: index,
  2932. label: s.xAxis.labels[index],
  2933. values: s.datasets.map(d => d.values[index])
  2934. };
  2935. return data_point;
  2936. }
  2937. setCurrentDataPoint(index) {
  2938. let s = this.state;
  2939. index = parseInt(index);
  2940. if(index < 0) index = 0;
  2941. if(index >= s.xAxis.labels.length) index = s.xAxis.labels.length - 1;
  2942. if(index === s.currentIndex) return;
  2943. s.currentIndex = index;
  2944. fire(this.parent, "data-select", this.getDataPoint());
  2945. }
  2946. // API
  2947. addDataPoint(label, datasetValues, index=this.state.datasetLength) {
  2948. super.addDataPoint(label, datasetValues, index);
  2949. this.data.labels.splice(index, 0, label);
  2950. this.data.datasets.map((d, i) => {
  2951. d.values.splice(index, 0, datasetValues[i]);
  2952. });
  2953. this.update(this.data);
  2954. }
  2955. removeDataPoint(index = this.state.datasetLength-1) {
  2956. if (this.data.labels.length <= 1) {
  2957. return;
  2958. }
  2959. super.removeDataPoint(index);
  2960. this.data.labels.splice(index, 1);
  2961. this.data.datasets.map(d => {
  2962. d.values.splice(index, 1);
  2963. });
  2964. this.update(this.data);
  2965. }
  2966. updateDataset(datasetValues, index=0) {
  2967. this.data.datasets[index].values = datasetValues;
  2968. this.update(this.data);
  2969. }
  2970. // addDataset(dataset, index) {}
  2971. // removeDataset(index = 0) {}
  2972. updateDatasets(datasets) {
  2973. this.data.datasets.map((d, i) => {
  2974. if(datasets[i]) {
  2975. d.values = datasets[i];
  2976. }
  2977. });
  2978. this.update(this.data);
  2979. }
  2980. // updateDataPoint(dataPoint, index = 0) {}
  2981. // addDataPoint(dataPoint, index = 0) {}
  2982. // removeDataPoint(index = 0) {}
  2983. }
  2984. const chartTypes = {
  2985. bar: AxisChart,
  2986. line: AxisChart,
  2987. // multiaxis: MultiAxisChart,
  2988. percentage: PercentageChart,
  2989. heatmap: Heatmap,
  2990. pie: PieChart
  2991. };
  2992. function getChartByType(chartType = 'line', parent, options) {
  2993. if (chartType === 'axis-mixed') {
  2994. options.type = 'line';
  2995. return new AxisChart(parent, options);
  2996. }
  2997. if (!chartTypes[chartType]) {
  2998. console.error("Undefined chart type: " + chartType);
  2999. return;
  3000. }
  3001. return new chartTypes[chartType](parent, options);
  3002. }
  3003. class Chart {
  3004. constructor(parent, options) {
  3005. return getChartByType(options.type, parent, options);
  3006. }
  3007. }
  3008. export { Chart, PercentageChart, PieChart, Heatmap, AxisChart };