Nie możesz wybrać więcej, niż 25 tematów Tematy muszą się zaczynać od litery lub cyfry, mogą zawierać myślniki ('-') i mogą mieć do 35 znaków.
 
 
 

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