Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.
 
 
 

3662 строки
86 KiB

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