25개 이상의 토픽을 선택하실 수 없습니다. Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

3711 lines
87 KiB

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