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

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